Search in sources :

Example 16 with EntitlementDTO

use of org.candlepin.dto.rules.v1.EntitlementDTO 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 17 with EntitlementDTO

use of org.candlepin.dto.rules.v1.EntitlementDTO 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 18 with EntitlementDTO

use of org.candlepin.dto.rules.v1.EntitlementDTO in project candlepin by candlepin.

the class EntitlementRules method preEntitlement.

@Override
@SuppressWarnings("checkstyle:indentation")
public Map<String, ValidationResult> preEntitlement(Consumer consumer, Consumer host, Collection<PoolQuantity> entitlementPoolQuantities, CallerType caller) {
    Map<String, ValidationResult> resultMap = new HashMap<>();
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
    /* This document describes the java script portion of the pre entitlement rules check:
         * http://www.candlepinproject.org/docs/candlepin/pre_entitlement_rules_check.html
         * As described in the document, none of the checks are related to share binds, so we
         * skip that step for share consumers.
         */
    if (!ctype.isType(ConsumerTypeEnum.SHARE)) {
        Stream<EntitlementDTO> entStream = consumer.getEntitlements() == null ? Stream.empty() : consumer.getEntitlements().stream().map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class));
        JsonJsContext args = new JsonJsContext(objectMapper);
        args.put("consumer", this.translator.translate(consumer, ConsumerDTO.class));
        args.put("hostConsumer", this.translator.translate(host, ConsumerDTO.class));
        args.put("consumerEntitlements", entStream.collect(Collectors.toSet()));
        args.put("standalone", config.getBoolean(ConfigProperties.STANDALONE));
        args.put("poolQuantities", entitlementPoolQuantities);
        args.put("caller", caller.getLabel());
        args.put("log", log, false);
        String json = jsRules.runJsFunction(String.class, "validate_pools_batch", args);
        TypeReference<Map<String, ValidationResult>> typeref = new TypeReference<Map<String, ValidationResult>>() {
        };
        try {
            resultMap = objectMapper.toObject(json, typeref);
            for (PoolQuantity poolQuantity : entitlementPoolQuantities) {
                if (!resultMap.containsKey(poolQuantity.getPool().getId())) {
                    resultMap.put(poolQuantity.getPool().getId(), new ValidationResult());
                    log.info("no result returned for pool: {}", poolQuantity.getPool());
                }
            }
        } catch (Exception e) {
            throw new RuleExecutionException(e);
        }
    }
    for (PoolQuantity poolQuantity : entitlementPoolQuantities) {
        if (ctype.isType(ConsumerTypeEnum.SHARE)) {
            ValidationResult result = new ValidationResult();
            resultMap.put(poolQuantity.getPool().getId(), result);
            validatePoolSharingEligibility(result, poolQuantity.getPool());
        }
        finishValidation(resultMap.get(poolQuantity.getPool().getId()), poolQuantity.getPool(), poolQuantity.getQuantity());
    }
    return resultMap;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) HashMap(java.util.HashMap) ValidationResult(org.candlepin.policy.ValidationResult) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException) EntitlementDTO(org.candlepin.dto.rules.v1.EntitlementDTO) ConsumerDTO(org.candlepin.dto.rules.v1.ConsumerDTO) JsonJsContext(org.candlepin.policy.js.JsonJsContext) TypeReference(com.fasterxml.jackson.core.type.TypeReference) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException) ConsumerType(org.candlepin.model.ConsumerType) Map(java.util.Map) HashMap(java.util.HashMap)

Example 19 with EntitlementDTO

use of org.candlepin.dto.rules.v1.EntitlementDTO in project candlepin by candlepin.

the class ComplianceRules method isStackCompliant.

@SuppressWarnings("checkstyle:indentation")
public boolean isStackCompliant(Consumer consumer, String stackId, List<Entitlement> entsToConsider) {
    Stream<EntitlementDTO> entStream = entsToConsider == null ? Stream.empty() : entsToConsider.stream().map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class));
    JsonJsContext args = new JsonJsContext(mapper);
    args.put("stack_id", stackId);
    args.put("consumer", this.translator.translate(consumer, ConsumerDTO.class));
    args.put("entitlements", entStream.collect(Collectors.toSet()));
    args.put("log", log, false);
    args.put("guestIds", consumer.getGuestIds());
    return jsRules.runJsFunction(Boolean.class, "is_stack_compliant", args);
}
Also used : EntitlementDTO(org.candlepin.dto.rules.v1.EntitlementDTO) ConsumerDTO(org.candlepin.dto.rules.v1.ConsumerDTO) JsonJsContext(org.candlepin.policy.js.JsonJsContext)

Example 20 with EntitlementDTO

use of org.candlepin.dto.rules.v1.EntitlementDTO in project candlepin by candlepin.

the class ComplianceRules method getStatus.

/**
 * Check compliance status for a consumer on a specific date.
 *
 * @param consumer Consumer to check.
 * @param date Date to check compliance status for.
 * @param calculateCompliantUntil calculate how long the system will remain compliant (expensive)
 * @param updateConsumer whether or not to use consumerCurator.update
 * @param calculateProductComplianceDateRanges calculate the individual compliance ranges for each product
 *        (also expensive)
 * @return Compliance status.
 */
@SuppressWarnings("checkstyle:indentation")
public ComplianceStatus getStatus(Consumer consumer, Collection<Entitlement> newEntitlements, Date date, boolean calculateCompliantUntil, boolean updateConsumer, boolean calculateProductComplianceDateRanges, boolean currentCompliance) {
    if (date == null) {
        date = new Date();
    }
    if (currentCompliance) {
        updateEntsOnStart(consumer);
    }
    Stream<EntitlementDTO> entStream = Stream.concat(newEntitlements != null ? newEntitlements.stream() : Stream.empty(), consumer.getEntitlements() != null ? consumer.getEntitlements().stream() : Stream.empty()).map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class));
    // Do not calculate compliance status for distributors and shares. It is prohibitively
    // expensive and meaningless
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
    if (ctype != null && (ctype.isManifest() || ctype.isType(ConsumerTypeEnum.SHARE))) {
        return new ComplianceStatus(new Date());
    }
    JsonJsContext args = new JsonJsContext(mapper);
    args.put("consumer", this.translator.translate(consumer, ConsumerDTO.class));
    args.put("entitlements", entStream.collect(Collectors.toSet()));
    args.put("ondate", date);
    args.put("calculateCompliantUntil", calculateCompliantUntil);
    args.put("calculateProductComplianceDateRanges", calculateProductComplianceDateRanges);
    args.put("log", log, false);
    args.put("guestIds", consumer.getGuestIds());
    // Convert the JSON returned into a ComplianceStatus object:
    String json = jsRules.runJsFunction(String.class, "get_status", args);
    try {
        ComplianceStatus status = mapper.toObject(json, ComplianceStatus.class);
        for (ComplianceReason reason : status.getReasons()) {
            generator.setMessage(consumer, reason, status.getDate());
        }
        if (currentCompliance) {
            applyStatus(consumer, status, updateConsumer);
        }
        return status;
    } catch (Exception e) {
        throw new RuleExecutionException(e);
    }
}
Also used : EntitlementDTO(org.candlepin.dto.rules.v1.EntitlementDTO) ConsumerDTO(org.candlepin.dto.rules.v1.ConsumerDTO) JsonJsContext(org.candlepin.policy.js.JsonJsContext) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException) Entitlement(org.candlepin.model.Entitlement) ConsumerType(org.candlepin.model.ConsumerType) Date(java.util.Date) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException)

Aggregations

Entitlement (org.candlepin.model.Entitlement)15 EntitlementDTO (org.candlepin.dto.api.v1.EntitlementDTO)11 ArrayList (java.util.ArrayList)10 List (java.util.List)8 Pool (org.candlepin.model.Pool)8 ConsumerDTO (org.candlepin.dto.rules.v1.ConsumerDTO)7 EntitlementDTO (org.candlepin.dto.rules.v1.EntitlementDTO)7 JsonJsContext (org.candlepin.policy.js.JsonJsContext)7 ApiOperation (io.swagger.annotations.ApiOperation)6 ApiResponses (io.swagger.annotations.ApiResponses)6 Produces (javax.ws.rs.Produces)6 Consumer (org.candlepin.model.Consumer)6 Test (org.junit.Test)6 Path (javax.ws.rs.Path)5 ConsumerType (org.candlepin.model.ConsumerType)5 EntitlementFilterBuilder (org.candlepin.model.EntitlementFilterBuilder)5 Owner (org.candlepin.model.Owner)5 LinkedList (java.util.LinkedList)4 GET (javax.ws.rs.GET)4 RuleExecutionException (org.candlepin.policy.js.RuleExecutionException)4