Search in sources :

Example 41 with NotFoundException

use of org.candlepin.common.exceptions.NotFoundException in project candlepin by candlepin.

the class EntitlementResource method hasEntitlement.

@ApiOperation(notes = "Checks Consumer for Product Entitlement", value = "hasEntitlement")
@ApiResponses({ @ApiResponse(code = 404, message = "") })
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("consumer/{consumer_uuid}/product/{product_id}")
public EntitlementDTO hasEntitlement(@PathParam("consumer_uuid") String consumerUuid, @PathParam("product_id") String productId) {
    Consumer consumer = consumerCurator.findByUuid(consumerUuid);
    verifyExistence(consumer, consumerUuid);
    for (Entitlement e : consumer.getEntitlements()) {
        if (e.getPool().getProductId().equals(productId)) {
            return this.translator.translate(e, EntitlementDTO.class);
        }
    }
    throw new NotFoundException(i18n.tr("Unit \"{0}\" has no subscription for product \"{1}\".", consumerUuid, productId));
}
Also used : Consumer(org.candlepin.model.Consumer) NotFoundException(org.candlepin.common.exceptions.NotFoundException) Entitlement(org.candlepin.model.Entitlement) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 42 with NotFoundException

use of org.candlepin.common.exceptions.NotFoundException in project candlepin by candlepin.

the class EntitlementResource method migrateEntitlement.

@ApiOperation(notes = "Migrate entitlements from one distributor consumer to another." + " Can specify full or partial quantity. No specified quantity " + "will lead to full migration of the entitlement.", value = "migrateEntitlement")
@ApiResponses({ @ApiResponse(code = 404, message = "") })
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.WILDCARD)
@Path("{entitlement_id}/migrate")
public Response migrateEntitlement(@PathParam("entitlement_id") @Verify(Entitlement.class) String id, @QueryParam("to_consumer") @Verify(Consumer.class) String uuid, @QueryParam("quantity") Integer quantity) {
    // confirm entitlement
    Entitlement entitlement = entitlementCurator.find(id);
    List<Entitlement> entitlements = new ArrayList<>();
    if (entitlement != null) {
        if (quantity == null) {
            quantity = entitlement.getQuantity();
        }
        if (quantity > 0 && quantity <= entitlement.getQuantity()) {
            Consumer sourceConsumer = entitlement.getConsumer();
            Consumer destinationConsumer = consumerCurator.verifyAndLookupConsumer(uuid);
            ConsumerType scType = this.consumerTypeCurator.getConsumerType(sourceConsumer);
            ConsumerType dcType = this.consumerTypeCurator.getConsumerType(destinationConsumer);
            if (!scType.isManifest()) {
                throw new BadRequestException(i18n.tr("Entitlement migration is not permissible for units of type \"{0}\"", scType.getLabel()));
            }
            if (!dcType.isManifest()) {
                throw new BadRequestException(i18n.tr("Entitlement migration is not permissible for units of type \"{0}\"", dcType.getLabel()));
            }
            if (!sourceConsumer.getOwnerId().equals(destinationConsumer.getOwnerId())) {
                throw new BadRequestException(i18n.tr("Source and destination units must belong to the same organization"));
            }
            // test to ensure destination can use the pool
            ValidationResult result = enforcer.preEntitlement(destinationConsumer, entitlement.getPool(), 0, CallerType.BIND);
            if (!result.isSuccessful()) {
                throw new BadRequestException(i18n.tr("The entitlement cannot be utilized by the destination unit: ") + messageTranslator.poolErrorToMessage(entitlement.getPool(), result.getErrors().get(0)));
            }
            if (quantity.intValue() == entitlement.getQuantity()) {
                unbind(id);
            } else {
                entitler.adjustEntitlementQuantity(sourceConsumer, entitlement, entitlement.getQuantity() - quantity);
            }
            Pool pool = entitlement.getPool();
            entitlements.addAll(entitler.bindByPoolQuantity(destinationConsumer, pool.getId(), quantity));
            // Trigger events:
            entitler.sendEvents(entitlements);
        } else {
            throw new BadRequestException(i18n.tr("The quantity specified must be greater than zero " + "and less than or equal to the total for this entitlement"));
        }
    } else {
        throw new NotFoundException(i18n.tr("Entitlement with ID \"{0}\" could not be found.", id));
    }
    List<EntitlementDTO> entitlementDTOs = new ArrayList<>();
    for (Entitlement entitlementModel : entitlements) {
        entitlementDTOs.add(this.translator.translate(entitlementModel, EntitlementDTO.class));
    }
    return Response.status(Response.Status.OK).type(MediaType.APPLICATION_JSON).entity(entitlementDTOs).build();
}
Also used : EntitlementDTO(org.candlepin.dto.api.v1.EntitlementDTO) Consumer(org.candlepin.model.Consumer) ArrayList(java.util.ArrayList) BadRequestException(org.candlepin.common.exceptions.BadRequestException) NotFoundException(org.candlepin.common.exceptions.NotFoundException) Pool(org.candlepin.model.Pool) Entitlement(org.candlepin.model.Entitlement) ConsumerType(org.candlepin.model.ConsumerType) ValidationResult(org.candlepin.policy.ValidationResult) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) PUT(javax.ws.rs.PUT)

Example 43 with NotFoundException

use of org.candlepin.common.exceptions.NotFoundException in project candlepin by candlepin.

the class ImportJob method toExecute.

@Override
public void toExecute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap map = context.getMergedJobDataMap();
    String ownerKey = (String) map.get(JobStatus.TARGET_ID);
    ConflictOverrides overrides = new ConflictOverrides((String[]) map.get(CONFLICT_OVERRIDES));
    String storedFileId = (String) map.get(STORED_FILE_ID);
    String uploadedFileName = (String) map.get(UPLOADED_FILE_NAME);
    Throwable caught = null;
    Owner targetOwner = null;
    try {
        targetOwner = ownerCurator.lookupByKey(ownerKey);
        if (targetOwner == null) {
            throw new NotFoundException(String.format("Owner %s was not found.", ownerKey));
        }
        ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName);
        context.setResult(importRecord);
    }// info about the exception that was thrown (CandlepinException).
     catch (SyncDataFormatException e) {
        caught = new BadRequestException(e.getMessage(), e);
    } catch (ImporterException e) {
        caught = new IseException(e.getMessage(), e);
    } catch (Exception e) {
        caught = e;
    }
    if (caught != null) {
        log.error("ImportJob encountered a problem.", caught);
        manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName);
        context.setResult(caught.getMessage());
        // If an exception was thrown, the importer's transaction was rolled
        // back. We want to make sure that the file gets deleted so that it
        // doesn't take up disk space. It may be possible that the file was
        // already deleted, but we attempt it anyway.
        manifestManager.deleteStoredManifest(storedFileId);
        throw new JobExecutionException(caught.getMessage(), caught, false);
    }
}
Also used : ImporterException(org.candlepin.sync.ImporterException) ConflictOverrides(org.candlepin.sync.ConflictOverrides) JobDataMap(org.quartz.JobDataMap) Owner(org.candlepin.model.Owner) SyncDataFormatException(org.candlepin.sync.SyncDataFormatException) NotFoundException(org.candlepin.common.exceptions.NotFoundException) ImportRecord(org.candlepin.model.ImportRecord) NotFoundException(org.candlepin.common.exceptions.NotFoundException) SyncDataFormatException(org.candlepin.sync.SyncDataFormatException) JobExecutionException(org.quartz.JobExecutionException) IseException(org.candlepin.common.exceptions.IseException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ImporterException(org.candlepin.sync.ImporterException) JobExecutionException(org.quartz.JobExecutionException) IseException(org.candlepin.common.exceptions.IseException) BadRequestException(org.candlepin.common.exceptions.BadRequestException)

Example 44 with NotFoundException

use of org.candlepin.common.exceptions.NotFoundException in project candlepin by candlepin.

the class ImportJobTest method ensureJobExceptionThrownIfOwnerNotFound.

@Test
public void ensureJobExceptionThrownIfOwnerNotFound() throws Exception {
    String archiveFilePath = "/path/to/some/file.zip";
    ConflictOverrides co = new ConflictOverrides();
    String uploadedFileName = "test.zip";
    String expectedMessage = String.format("Owner %s was not found.", owner.getKey());
    JobDetail detail = job.scheduleImport(owner, archiveFilePath, uploadedFileName, co);
    when(ctx.getMergedJobDataMap()).thenReturn(detail.getJobDataMap());
    when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(null);
    try {
        job.execute(ctx);
        fail("Expected exception not thrown");
    } catch (JobExecutionException je) {
        Throwable cause = je.getCause();
        assertTrue(cause instanceof NotFoundException);
    }
    verify(ctx).setResult(eq(expectedMessage));
}
Also used : ConflictOverrides(org.candlepin.sync.ConflictOverrides) JobDetail(org.quartz.JobDetail) JobExecutionException(org.quartz.JobExecutionException) NotFoundException(org.candlepin.common.exceptions.NotFoundException) Test(org.junit.Test)

Aggregations

NotFoundException (org.candlepin.common.exceptions.NotFoundException)44 ApiOperation (io.swagger.annotations.ApiOperation)25 Produces (javax.ws.rs.Produces)25 ApiResponses (io.swagger.annotations.ApiResponses)24 Path (javax.ws.rs.Path)22 BadRequestException (org.candlepin.common.exceptions.BadRequestException)16 Consumer (org.candlepin.model.Consumer)12 Owner (org.candlepin.model.Owner)12 DELETE (javax.ws.rs.DELETE)11 GET (javax.ws.rs.GET)10 Entitlement (org.candlepin.model.Entitlement)10 Pool (org.candlepin.model.Pool)9 ArrayList (java.util.ArrayList)7 Transactional (com.google.inject.persist.Transactional)6 Consumes (javax.ws.rs.Consumes)6 ConsumerType (org.candlepin.model.ConsumerType)6 PUT (javax.ws.rs.PUT)5 ForbiddenException (org.candlepin.common.exceptions.ForbiddenException)5 Environment (org.candlepin.model.Environment)5 Test (org.junit.Test)5