Search in sources :

Example 61 with BadRequestException

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

the class SubscriptionResource method activateSubscription.

@ApiOperation(notes = "Activates a Subscription", value = "activateSubscription")
@ApiResponses({ @ApiResponse(code = 400, message = ""), @ApiResponse(code = 503, message = ""), @ApiResponse(code = 202, message = "") })
@POST
@Produces(MediaType.WILDCARD)
@Consumes(MediaType.WILDCARD)
public Response activateSubscription(@ApiParam(required = true) @QueryParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid, @ApiParam(required = true) @QueryParam("email") String email, @ApiParam(required = true) @QueryParam("email_locale") String emailLocale) {
    if (email == null) {
        throw new BadRequestException(i18n.tr("email is required for notification"));
    }
    if (emailLocale == null) {
        throw new BadRequestException(i18n.tr("email locale is required for notification"));
    }
    Consumer consumer = consumerCurator.findByUuid(consumerUuid);
    if (consumer == null) {
        throw new BadRequestException(i18n.tr("No such unit: {0}", consumerUuid));
    }
    this.subService.activateSubscription(consumer, email, emailLocale);
    // exist yet, but is currently being processed
    return Response.status(Status.ACCEPTED).build();
}
Also used : Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 62 with BadRequestException

use of org.candlepin.common.exceptions.BadRequestException 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 63 with BadRequestException

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

the class EntitlementResource method listAllForConsumer.

@ApiOperation(notes = "Retrieves list of Entitlements", value = "listAllForConsumer")
@ApiResponses({ @ApiResponse(code = 400, message = "") })
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<EntitlementDTO> listAllForConsumer(@QueryParam("consumer") String consumerUuid, @QueryParam("matches") String matches, @QueryParam("attribute") @CandlepinParam(type = KeyValueParameter.class) List<KeyValueParameter> attrFilters, @Context PageRequest pageRequest) {
    EntitlementFilterBuilder filters = EntitlementFinderUtil.createFilter(matches, attrFilters);
    Page<List<Entitlement>> p;
    if (consumerUuid != null) {
        Consumer consumer = consumerCurator.findByUuid(consumerUuid);
        if (consumer == null) {
            throw new BadRequestException(i18n.tr("Unit with ID \"{0}\" could not be found.", consumerUuid));
        }
        p = entitlementCurator.listByConsumer(consumer, null, filters, pageRequest);
    } else {
        p = entitlementCurator.listAll(filters, pageRequest);
    }
    // Store the page for the LinkHeaderResponseFilter
    ResteasyProviderFactory.pushContext(Page.class, p);
    List<EntitlementDTO> entitlementDTOs = new ArrayList<>();
    for (Entitlement entitlement : p.getPageData()) {
        entitlementDTOs.add(this.translator.translate(entitlement, EntitlementDTO.class));
    }
    return entitlementDTOs;
}
Also used : EntitlementDTO(org.candlepin.dto.api.v1.EntitlementDTO) Consumer(org.candlepin.model.Consumer) EntitlementFilterBuilder(org.candlepin.model.EntitlementFilterBuilder) ArrayList(java.util.ArrayList) BadRequestException(org.candlepin.common.exceptions.BadRequestException) List(java.util.List) ArrayList(java.util.ArrayList) Entitlement(org.candlepin.model.Entitlement) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 64 with BadRequestException

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

the class HypervisorResource method hypervisorUpdate.

/**
 * @deprecated Use the asynchronous method
 * @return HypervisorCheckInResult
 */
@ApiOperation(notes = "Updates the list of Hypervisor Guests Allows agents such as " + "virt-who to update its host list and associate the guests for each host. This is " + "typically used when a host is unable to register to candlepin via subscription" + " manager.  In situations where consumers already exist it is probably best not " + "to allow creation of new hypervisor consumers.  Most consumers do not have a" + " hypervisorId attribute, so that should be added manually when necessary by the " + "management environment. @deprecated Use the asynchronous method", value = "hypervisorUpdate")
@ApiResponses({ @ApiResponse(code = 202, message = "") })
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Deprecated
@Transactional
@UpdateConsumerCheckIn
@SuppressWarnings("checkstyle:indentation")
public HypervisorCheckInResult hypervisorUpdate(Map<String, List<GuestIdDTO>> hostGuestDTOMap, @Context Principal principal, @QueryParam("owner") @Verify(value = Owner.class, require = Access.READ_ONLY, subResource = SubResource.HYPERVISOR) String ownerKey, @ApiParam("specify whether or not to create missing hypervisors." + "Default is true.  If false is specified, hypervisorIds that are not found" + "will result in failed entries in the resulting HypervisorCheckInResult") @QueryParam("create_missing") @DefaultValue("true") boolean createMissing) {
    log.debug("Hypervisor check-in by principal: {}", principal);
    if (hostGuestDTOMap == null) {
        log.debug("Host/Guest mapping provided during hypervisor checkin was null.");
        throw new BadRequestException(i18n.tr("Host to guest mapping was not provided for hypervisor check-in."));
    }
    Owner owner = this.getOwner(ownerKey);
    if (owner.isAutobindDisabled()) {
        log.debug("Could not update host/guest mapping. Auto-attach is disabled for owner {}", owner.getKey());
        throw new BadRequestException(i18n.tr("Could not update host/guest mapping. Auto-attach is disabled for owner {0}.", owner.getKey()));
    }
    if (hostGuestDTOMap.remove("") != null) {
        log.warn("Ignoring empty hypervisor id");
    }
    // Maps virt hypervisor ID to registered consumer for that hypervisor, should one exist:
    VirtConsumerMap hypervisorConsumersMap = consumerCurator.getHostConsumersMap(owner, hostGuestDTOMap.keySet());
    int emptyGuestIdCount = 0;
    Set<String> allGuestIds = new HashSet<>();
    Collection<List<GuestIdDTO>> idsLists = hostGuestDTOMap.values();
    for (List<GuestIdDTO> guestIds : idsLists) {
        // See bzs 1332637, 1332635
        if (guestIds == null) {
            continue;
        }
        for (Iterator<GuestIdDTO> guestIdsItr = guestIds.iterator(); guestIdsItr.hasNext(); ) {
            String id = guestIdsItr.next().getGuestId();
            if (StringUtils.isEmpty(id)) {
                emptyGuestIdCount++;
                guestIdsItr.remove();
            } else {
                allGuestIds.add(id);
            }
        }
    }
    if (emptyGuestIdCount > 0) {
        log.warn("Ignoring {} empty/null guest id(s).", emptyGuestIdCount);
    }
    HypervisorCheckInResult result = new HypervisorCheckInResult();
    for (Entry<String, List<GuestIdDTO>> hostEntry : hostGuestDTOMap.entrySet()) {
        String hypervisorId = hostEntry.getKey();
        // See bzs 1332637, 1332635
        if (hostEntry.getValue() == null) {
            hostEntry.setValue(new ArrayList<>());
        }
        try {
            log.debug("Syncing virt host: {} ({} guest IDs)", hypervisorId, hostEntry.getValue().size());
            boolean hostConsumerCreated = false;
            boolean updatedType = false;
            // Attempt to find a consumer for the given hypervisorId
            Consumer consumer = null;
            if (hypervisorConsumersMap.get(hypervisorId) == null) {
                if (!createMissing) {
                    log.info("Unable to find hypervisor with id {} in org {}", hypervisorId, ownerKey);
                    result.failed(hypervisorId, i18n.tr("Unable to find hypervisor in org \"{0}\"", ownerKey));
                    continue;
                }
                log.debug("Registering new host consumer for hypervisor ID: {}", hypervisorId);
                consumer = createConsumerForHypervisorId(hypervisorId, owner, principal);
                hostConsumerCreated = true;
            } else {
                consumer = hypervisorConsumersMap.get(hypervisorId);
                if (!hypervisorType.getId().equals(consumer.getTypeId())) {
                    consumer.setType(hypervisorType);
                    updatedType = true;
                }
            }
            List<GuestId> guestIds = new ArrayList<>();
            guestIdResource.populateEntities(guestIds, hostEntry.getValue());
            boolean guestIdsUpdated = addGuestIds(consumer, guestIds);
            Date now = new Date();
            consumerCurator.updateLastCheckin(consumer, now);
            consumer.setLastCheckin(now);
            // Populate the result with the processed consumer.
            if (hostConsumerCreated) {
                result.created(consumer);
            } else if (guestIdsUpdated || updatedType) {
                result.updated(consumer);
            } else {
                result.unchanged(consumer);
            }
        } catch (Exception e) {
            log.error("Hypervisor checkin failed", e);
            result.failed(hypervisorId, e.getMessage());
        }
    }
    log.info("Summary of hypervisor checkin by principal \"{}\": {}", principal, result);
    return result;
}
Also used : GuestIdDTO(org.candlepin.dto.api.v1.GuestIdDTO) Owner(org.candlepin.model.Owner) ArrayList(java.util.ArrayList) Date(java.util.Date) NotFoundException(org.candlepin.common.exceptions.NotFoundException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) Consumer(org.candlepin.model.Consumer) VirtConsumerMap(org.candlepin.model.VirtConsumerMap) GuestId(org.candlepin.model.GuestId) BadRequestException(org.candlepin.common.exceptions.BadRequestException) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) HypervisorCheckInResult(org.candlepin.resource.dto.HypervisorCheckInResult) UpdateConsumerCheckIn(org.candlepin.auth.UpdateConsumerCheckIn) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) Transactional(com.google.inject.persist.Transactional)

Example 65 with BadRequestException

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

the class ResourceDateParser method getFromDate.

public static Date getFromDate(String from, String to, String days) {
    if (days != null && !days.trim().equals("") && (to != null && !to.trim().equals("") || from != null && !from.trim().equals(""))) {
        throw new BadRequestException("You can use either the to/from date parameters or the number of days parameter, but not both");
    }
    Date daysDate = null;
    if (days != null && !days.trim().equals("")) {
        long mills = 1000L * 60 * 60 * 24;
        int number = Integer.parseInt(days);
        daysDate = new Date(new Date().getTime() - (number * mills));
    }
    Date fromDate = null;
    if (daysDate != null) {
        fromDate = daysDate;
    } else {
        fromDate = parseDateString(from);
    }
    return fromDate;
}
Also used : BadRequestException(org.candlepin.common.exceptions.BadRequestException) Date(java.util.Date)

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