Search in sources :

Example 26 with BadRequestException

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

the class ConsumerResource method generateIdCert.

/**
 * Generates the identity certificate for the given consumer and user.
 * Throws RuntimeException if there is a problem with generating the
 * certificate.
 * <p>
 * Regenerating an Id Cert is ok to do at any time. Since we only check
 * that the cert's date range is valid, and that it is signed by us,
 * and that the consumer UUID is in our db, it doesn't matter if the actual
 * cert itself is the one stored in our db (and therefore the most recent
 * version) or not.
 *
 * @param c Consumer whose certificate needs to be generated.
 * @param regen if true, forces a regen of the certificate.
 * @return an IdentityCertificate object
 */
private IdentityCertificate generateIdCert(Consumer c, boolean regen) {
    IdentityCertificate idCert = null;
    boolean errored = false;
    try {
        if (regen) {
            idCert = identityCertService.regenerateIdentityCert(c);
        } else {
            idCert = identityCertService.generateIdentityCert(c);
        }
        if (idCert == null) {
            errored = true;
        }
    } catch (GeneralSecurityException e) {
        log.error("Problem regenerating ID cert for unit:", e);
        errored = true;
    } catch (IOException e) {
        log.error("Problem regenerating ID cert for unit:", e);
        errored = true;
    }
    if (errored) {
        throw new BadRequestException(i18n.tr("Problem regenerating ID cert for unit {0}", c));
    }
    log.debug("Generated identity cert: {}", idCert.getSerial());
    return idCert;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) IOException(java.io.IOException) IdentityCertificate(org.candlepin.model.IdentityCertificate)

Example 27 with BadRequestException

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

the class ConsumerResource method performConsumerUpdates.

@Transactional
public boolean performConsumerUpdates(ConsumerDTO updated, Consumer toUpdate, GuestMigration guestMigration, boolean isIdCert) {
    log.debug("Updating consumer: {}", toUpdate.getUuid());
    // We need a representation of the consumer before making any modifications.
    // If nothing changes we won't send.  The new entity needs to be correct though,
    // so we should get a Jsonstring now, and finish it off if we're going to send
    EventBuilder eventBuilder = eventFactory.getEventBuilder(Target.CONSUMER, Type.MODIFIED).setEventData(toUpdate);
    // version changed on non-checked in consumer, or list of capabilities
    // changed on checked in consumer
    boolean changesMade = updateCapabilities(toUpdate, updated);
    changesMade = checkForFactsUpdate(toUpdate, updated) || changesMade;
    changesMade = checkForInstalledProductsUpdate(toUpdate, updated) || changesMade;
    changesMade = checkForHypervisorIdUpdate(toUpdate, updated) || changesMade;
    changesMade = guestMigration.isMigrationPending() || changesMade;
    if (updated.getContentTags() != null && !updated.getContentTags().equals(toUpdate.getContentTags())) {
        log.info("   Updating content tags.");
        toUpdate.setContentTags(updated.getContentTags());
        changesMade = true;
    }
    // Allow optional setting of the autoheal attribute:
    if (updated.getAutoheal() != null && !updated.getAutoheal().equals(toUpdate.isAutoheal())) {
        log.info("   Updating consumer autoheal setting.");
        toUpdate.setAutoheal(updated.getAutoheal());
        changesMade = true;
    }
    if (updated.getReleaseVersion() != null && !updated.getReleaseVersion().equals(toUpdate.getReleaseVer() == null ? null : toUpdate.getReleaseVer().getReleaseVer())) {
        log.info("   Updating consumer releaseVer setting.");
        toUpdate.setReleaseVer(new Release(updated.getReleaseVersion()));
        changesMade = true;
    }
    // Allow optional setting of the service level attribute:
    String level = updated.getServiceLevel();
    if (level != null && !level.equals(toUpdate.getServiceLevel())) {
        log.info("   Updating consumer service level setting.");
        consumerBindUtil.validateServiceLevel(toUpdate.getOwnerId(), level);
        toUpdate.setServiceLevel(level);
        changesMade = true;
    }
    String environmentId = updated.getEnvironment() == null ? null : updated.getEnvironment().getId();
    if (environmentId != null && (toUpdate.getEnvironmentId() == null || !toUpdate.getEnvironmentId().equals(environmentId))) {
        Environment e = environmentCurator.find(environmentId);
        if (e == null) {
            throw new NotFoundException(i18n.tr("Environment with ID \"{0}\" could not be found.", environmentId));
        }
        log.info("Updating environment to: {}", environmentId);
        toUpdate.setEnvironment(e);
        // lazily regenerate certs, so the client can still work
        poolManager.regenerateCertificatesOf(toUpdate, true);
        changesMade = true;
    }
    // it should remain the same
    if (updated.getName() != null && !toUpdate.getName().equals(updated.getName())) {
        checkConsumerName(updated);
        log.info("Updating consumer name: {} -> {}", toUpdate.getName(), updated.getName());
        toUpdate.setName(updated.getName());
        changesMade = true;
        // get the new name into the id cert if we are using the cert
        if (isIdCert) {
            IdentityCertificate ic = generateIdCert(toUpdate, true);
            toUpdate.setIdCert(ic);
        }
    }
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(toUpdate);
    if (updated.getContentAccessMode() != null && !updated.getContentAccessMode().equals(toUpdate.getContentAccessMode()) && ctype.isManifest()) {
        Owner toUpdateOwner = ownerCurator.findOwnerById(toUpdate.getOwnerId());
        if (!toUpdateOwner.isAllowedContentAccessMode(updated.getContentAccessMode())) {
            throw new BadRequestException(i18n.tr("The consumer cannot use the supplied content access mode."));
        }
        toUpdate.setContentAccessMode(updated.getContentAccessMode());
        changesMade = true;
    }
    if (!StringUtils.isEmpty(updated.getContentAccessMode()) && !ctype.isManifest()) {
        throw new BadRequestException(i18n.tr("The consumer cannot be assigned a content access mode."));
    }
    if (updated.getLastCheckin() != null) {
        log.info("Updating to specific last checkin time: {}", updated.getLastCheckin());
        toUpdate.setLastCheckin(updated.getLastCheckin());
        changesMade = true;
    }
    if (changesMade) {
        log.debug("Consumer {} updated.", toUpdate.getUuid());
        // Set the updated date here b/c @PreUpdate will not get fired
        // since only the facts table will receive the update.
        toUpdate.setUpdated(new Date());
        // this should update compliance on toUpdate, but not call the curator
        complianceRules.getStatus(toUpdate, null, false, false);
        Event event = eventBuilder.setEventData(toUpdate).buildEvent();
        sink.queueEvent(event);
    }
    return changesMade;
}
Also used : Owner(org.candlepin.model.Owner) EventBuilder(org.candlepin.audit.EventBuilder) Environment(org.candlepin.model.Environment) NotFoundException(org.candlepin.common.exceptions.NotFoundException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) Event(org.candlepin.audit.Event) ConsumerType(org.candlepin.model.ConsumerType) Release(org.candlepin.model.Release) Date(java.util.Date) IdentityCertificate(org.candlepin.model.IdentityCertificate) Transactional(com.google.inject.persist.Transactional)

Example 28 with BadRequestException

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

the class ConsumerResource method getEntitlementCertificates.

@ApiOperation(notes = "Retrieves a list of Entitlement Certificates for the Consumer", value = "getEntitlementCertificates")
@ApiResponses({ @ApiResponse(code = 404, message = "") })
@GET
@Path("{consumer_uuid}/certificates")
@Produces(MediaType.APPLICATION_JSON)
@UpdateConsumerCheckIn
public List<CertificateDTO> getEntitlementCertificates(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid, @QueryParam("serials") String serials) {
    log.debug("Getting client certificates for consumer: {}", consumerUuid);
    Consumer consumer = consumerCurator.verifyAndLookupConsumer(consumerUuid);
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
    if (ctype.isType(ConsumerTypeEnum.SHARE)) {
        logShareConsumerRequestWarning("cert fetch", consumer);
        return new ArrayList<>();
    }
    revokeOnGuestMigration(consumer);
    poolManager.regenerateDirtyEntitlements(consumer);
    Set<Long> serialSet = this.extractSerials(serials);
    List<CertificateDTO> returnCerts = new LinkedList<>();
    List<EntitlementCertificate> allCerts = entCertService.listForConsumer(consumer);
    for (EntitlementCertificate cert : allCerts) {
        if (serialSet.isEmpty() || serialSet.contains(cert.getSerial().getId())) {
            returnCerts.add(translator.translate(cert, CertificateDTO.class));
        }
    }
    // we want to insert the content access cert to this list if appropriate
    try {
        Certificate cert = contentAccessCertService.getCertificate(consumer);
        if (cert != null) {
            returnCerts.add(translator.translate(cert, CertificateDTO.class));
        }
    } catch (IOException ioe) {
        throw new BadRequestException(i18n.tr("Cannot retrieve content access certificate"), ioe);
    } catch (GeneralSecurityException gse) {
        throw new BadRequestException(i18n.tr("Cannot retrieve content access certificate"), gse);
    }
    return returnCerts;
}
Also used : EntitlementCertificate(org.candlepin.model.EntitlementCertificate) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) LinkedList(java.util.LinkedList) CertificateDTO(org.candlepin.dto.api.v1.CertificateDTO) DeletedConsumer(org.candlepin.model.DeletedConsumer) Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ConsumerType(org.candlepin.model.ConsumerType) EntitlementCertificate(org.candlepin.model.EntitlementCertificate) IdentityCertificate(org.candlepin.model.IdentityCertificate) Certificate(org.candlepin.model.Certificate) ContentAccessCertificate(org.candlepin.model.ContentAccessCertificate) Path(javax.ws.rs.Path) UpdateConsumerCheckIn(org.candlepin.auth.UpdateConsumerCheckIn) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 29 with BadRequestException

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

the class ConsumerResource method dryBind.

@ApiOperation(notes = "Retrieves a list of Pools and quantities that would be the " + "result of an auto-bind. This is a dry run of an autobind. It allows the client " + "to see what would be the result of an autobind without executing it. It can only" + " do this for the prevously established list of installed products for the consumer" + " If a service level is included in the request, then that level will override " + "the one stored on the consumer. If no service level is included then the existing " + "one will be used. The Response has a list of PoolQuantity objects", value = "dryBind")
@ApiResponses({ @ApiResponse(code = 400, message = ""), @ApiResponse(code = 403, message = ""), @ApiResponse(code = 404, message = "") })
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{consumer_uuid}/entitlements/dry-run")
public List<PoolQuantityDTO> dryBind(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid, @QueryParam("service_level") String serviceLevel) {
    // Verify consumer exists:
    Consumer consumer = consumerCurator.verifyAndLookupConsumer(consumerUuid);
    Owner owner = ownerCurator.findOwnerById(consumer.getOwnerId());
    if (owner.isAutobindDisabled()) {
        throw new BadRequestException(i18n.tr("Owner has autobind disabled."));
    }
    List<PoolQuantity> dryRunPools = new ArrayList<>();
    try {
        consumerBindUtil.validateServiceLevel(consumer.getOwnerId(), serviceLevel);
        dryRunPools = entitler.getDryRun(consumer, owner, serviceLevel);
    } catch (ForbiddenException fe) {
        return Collections.<PoolQuantityDTO>emptyList();
    } catch (BadRequestException bre) {
        throw bre;
    } catch (RuntimeException re) {
        return Collections.<PoolQuantityDTO>emptyList();
    }
    if (dryRunPools != null) {
        List<PoolQuantityDTO> dryRunPoolDtos = new ArrayList<>();
        for (PoolQuantity pq : dryRunPools) {
            dryRunPoolDtos.add(this.translator.translate(pq, PoolQuantityDTO.class));
        }
        return dryRunPoolDtos;
    } else {
        return Collections.<PoolQuantityDTO>emptyList();
    }
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Owner(org.candlepin.model.Owner) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) DeletedConsumer(org.candlepin.model.DeletedConsumer) Consumer(org.candlepin.model.Consumer) ArrayList(java.util.ArrayList) BadRequestException(org.candlepin.common.exceptions.BadRequestException) PoolQuantityDTO(org.candlepin.dto.api.v1.PoolQuantityDTO) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 30 with BadRequestException

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

the class ConsumerResource method downloadExistingExport.

/**
 * Downloads an asynchronously generated consumer export file (manifest). If the file
 * was successfully downloaded, it will be deleted.
 *
 * @param response
 * @param consumerUuid the UUID of the target consumer.
 * @param exportId the id of the stored export.
 */
@ApiOperation(notes = "Downloads an asynchronously generated consumer export file (manifest).", value = "Async Consumer Export (manifest) Download", response = File.class)
@ApiResponses({ @ApiResponse(code = 403, message = ""), @ApiResponse(code = 500, message = ""), @ApiResponse(code = 404, message = "") })
@GET
@Produces("application/zip")
@Path("{consumer_uuid}/export/{export_id}")
public void downloadExistingExport(@Context HttpServletResponse response, @PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid, @PathParam("export_id") String exportId) {
    Consumer consumer = consumerCurator.verifyAndLookupConsumer(consumerUuid);
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
    if (ctype.isType(ConsumerTypeEnum.SHARE)) {
        throw new BadRequestException(i18n.tr("Can not export manifest of a share consumer"));
    }
    // *******************************************************************************
    // NOTE: If changing the path or parameters of this end point, be sure to update
    // the HREF generation in ConsumerResource.buildAsyncDownloadManifestHref.
    // *******************************************************************************
    // The response for this request is formulated a little different for this
    // file download. In some cases, such as for a hibernate DB file service, we must
    // stream the results from the DB to the client by directly writing to the
    // response output stream.
    // 
    // NOTE: Passing the database input stream to the response builder seems
    // like it would be a correct approach here, but large object streaming
    // can only be done inside a single transaction, so we have to stream it
    // manually.
    // TODO See if there is a way to get RestEasy to do this so we don't have to.
    manifestManager.writeStoredExportToResponse(exportId, consumerUuid, response);
    // On successful manifest read, delete the record. The manifest can only be
    // downloaded once and must then be regenerated.
    manifestManager.deleteStoredManifest(exportId);
}
Also used : DeletedConsumer(org.candlepin.model.DeletedConsumer) Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) ConsumerType(org.candlepin.model.ConsumerType) 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)

Aggregations

BadRequestException (org.candlepin.common.exceptions.BadRequestException)69 ApiOperation (io.swagger.annotations.ApiOperation)38 Produces (javax.ws.rs.Produces)38 ApiResponses (io.swagger.annotations.ApiResponses)36 Owner (org.candlepin.model.Owner)33 Path (javax.ws.rs.Path)28 Consumer (org.candlepin.model.Consumer)27 Consumes (javax.ws.rs.Consumes)24 NotFoundException (org.candlepin.common.exceptions.NotFoundException)21 POST (javax.ws.rs.POST)15 ConsumerType (org.candlepin.model.ConsumerType)15 Transactional (com.google.inject.persist.Transactional)14 DeletedConsumer (org.candlepin.model.DeletedConsumer)14 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 GET (javax.ws.rs.GET)13 ForbiddenException (org.candlepin.common.exceptions.ForbiddenException)11 PUT (javax.ws.rs.PUT)9 IseException (org.candlepin.common.exceptions.IseException)9 ActivationKey (org.candlepin.model.activationkeys.ActivationKey)9