Search in sources :

Example 21 with PoolDTO

use of org.candlepin.dto.api.v1.PoolDTO in project candlepin by candlepin.

the class PoolResourceTest method testListForOrg.

@Test
public void testListForOrg() {
    List<PoolDTO> pools = poolResource.list(owner1.getId(), null, null, false, null, adminPrincipal, null);
    assertEquals(2, pools.size());
    Principal p = setupPrincipal(owner2, Access.ALL);
    pools = poolResource.list(owner2.getId(), null, null, false, null, p, null);
    assertEquals(1, pools.size());
}
Also used : PoolDTO(org.candlepin.dto.api.v1.PoolDTO) Principal(org.candlepin.auth.Principal) ConsumerPrincipal(org.candlepin.auth.ConsumerPrincipal) Test(org.junit.Test)

Example 22 with PoolDTO

use of org.candlepin.dto.api.v1.PoolDTO in project candlepin by candlepin.

the class EntitlementImporter method populateEntity.

/**
 * Populates the specified entity with data from the provided DTO.
 *
 * @param entity
 *  The entity instance to populate
 *
 * @param dto
 *  The DTO containing the data with which to populate the entity
 *
 * @throws IllegalArgumentException
 *  if either entity or dto are null
 */
@SuppressWarnings("checkstyle:methodlength")
private void populateEntity(Entitlement entity, EntitlementDTO dto) {
    if (entity == null) {
        throw new IllegalArgumentException("the entitlement model entity is null");
    }
    if (dto == null) {
        throw new IllegalArgumentException("the entitlement dto is null");
    }
    if (dto.getId() != null) {
        entity.setId(dto.getId());
    }
    if (dto.getQuantity() != null) {
        entity.setQuantity(dto.getQuantity());
    }
    if (dto.getUpdated() != null) {
        entity.setUpdated(dto.getUpdated());
    }
    if (dto.getCreated() != null) {
        entity.setCreated(dto.getCreated());
    }
    if (dto.getStartDate() != null) {
        entity.setStartDate(dto.getStartDate());
    }
    if (dto.getEndDate() != null) {
        entity.setEndDate(dto.getEndDate());
    }
    if (dto.getPool() != null) {
        PoolDTO poolDTO = dto.getPool();
        Pool poolEntity = new Pool();
        if (poolDTO.getId() != null) {
            poolEntity.setId(poolDTO.getId());
        }
        if (poolDTO.getQuantity() != null) {
            poolEntity.setQuantity(poolDTO.getQuantity());
        }
        if (poolDTO.isActiveSubscription() != null) {
            poolEntity.setActiveSubscription(poolDTO.isActiveSubscription());
        }
        if (poolDTO.isCreatedByShare() != null) {
            poolEntity.setCreatedByShare(poolDTO.isCreatedByShare());
        }
        if (poolDTO.hasSharedAncestor() != null) {
            poolEntity.setHasSharedAncestor(poolDTO.hasSharedAncestor());
        }
        if (poolDTO.getRestrictedToUsername() != null) {
            poolEntity.setRestrictedToUsername(poolDTO.getRestrictedToUsername());
        }
        if (poolDTO.getConsumed() != null) {
            poolEntity.setConsumed(poolDTO.getConsumed());
        }
        if (poolDTO.getExported() != null) {
            poolEntity.setExported(poolDTO.getExported());
        }
        if (poolDTO.getShared() != null) {
            poolEntity.setShared(poolDTO.getShared());
        }
        if (poolDTO.getStackId() != null && poolDTO.getSourceStackId() != null) {
            SourceStack sourceStack = new SourceStack();
            sourceStack.setId(poolDTO.getStackId());
            sourceStack.setSourceStackId(poolDTO.getSourceStackId());
            poolEntity.setSourceStack(sourceStack);
        }
        if (poolDTO.getProductId() != null) {
            poolEntity.setProductId(poolDTO.getProductId());
        }
        if (poolDTO.getDerivedProductId() != null) {
            poolEntity.setDerivedProductId(poolDTO.getDerivedProductId());
        }
        if (poolDTO.getStartDate() != null) {
            poolEntity.setStartDate(poolDTO.getStartDate());
        }
        if (poolDTO.getEndDate() != null) {
            poolEntity.setEndDate(poolDTO.getEndDate());
        }
        if (poolDTO.getCreated() != null) {
            poolEntity.setCreated(poolDTO.getCreated());
        }
        if (poolDTO.getUpdated() != null) {
            poolEntity.setUpdated(poolDTO.getUpdated());
        }
        if (poolDTO.getAccountNumber() != null) {
            poolEntity.setAccountNumber(poolDTO.getAccountNumber());
        }
        if (poolDTO.getOrderNumber() != null) {
            poolEntity.setOrderNumber(poolDTO.getOrderNumber());
        }
        if (poolDTO.getContractNumber() != null) {
            poolEntity.setContractNumber(poolDTO.getContractNumber());
        }
        if (poolDTO.getOwner() != null) {
            Owner ownerEntity = new Owner();
            populateEntity(ownerEntity, poolDTO.getOwner());
            poolEntity.setOwner(ownerEntity);
        }
        if (poolDTO.getUpstreamPoolId() != null) {
            poolEntity.setUpstreamPoolId(poolDTO.getUpstreamPoolId());
        }
        if (poolDTO.getUpstreamConsumerId() != null) {
            poolEntity.setUpstreamConsumerId(poolDTO.getUpstreamConsumerId());
        }
        if (poolDTO.getUpstreamEntitlementId() != null) {
            poolEntity.setUpstreamEntitlementId(poolDTO.getUpstreamEntitlementId());
        }
        if (poolDTO.getSourceEntitlement() != null) {
            EntitlementDTO sourceEntitlementDTO = poolDTO.getSourceEntitlement();
            poolEntity.setSourceEntitlement(findEntitlement(sourceEntitlementDTO.getId()));
        }
        if (poolDTO.getSubscriptionSubKey() != null) {
            poolEntity.setSubscriptionSubKey(poolDTO.getSubscriptionSubKey());
        }
        if (poolDTO.getSubscriptionId() != null) {
            poolEntity.setSubscriptionId(poolDTO.getSubscriptionId());
        }
        if (poolDTO.getAttributes() != null) {
            if (poolDTO.getAttributes().isEmpty()) {
                poolEntity.setAttributes(Collections.emptyMap());
            } else {
                poolEntity.setAttributes(poolDTO.getAttributes());
            }
        }
        if (poolDTO.getCalculatedAttributes() != null) {
            if (poolDTO.getCalculatedAttributes().isEmpty()) {
                poolEntity.setCalculatedAttributes(Collections.emptyMap());
            } else {
                poolEntity.setCalculatedAttributes(poolDTO.getCalculatedAttributes());
            }
        }
        if (poolDTO.getProductAttributes() != null) {
            if (poolDTO.getProductAttributes().isEmpty()) {
                poolEntity.setProductAttributes(Collections.emptyMap());
            } else {
                poolEntity.setProductAttributes(poolDTO.getProductAttributes());
            }
        }
        if (poolDTO.getDerivedProductAttributes() != null) {
            if (poolDTO.getDerivedProductAttributes().isEmpty()) {
                poolEntity.setDerivedProductAttributes(Collections.emptyMap());
            } else {
                poolEntity.setDerivedProductAttributes(poolDTO.getDerivedProductAttributes());
            }
        }
        if (poolDTO.getBranding() != null) {
            if (poolDTO.getBranding().isEmpty()) {
                poolEntity.setBranding(Collections.emptySet());
            } else {
                Set<Branding> branding = new HashSet<>();
                for (BrandingDTO brandingDTO : poolDTO.getBranding()) {
                    if (brandingDTO != null) {
                        Branding brandingEntity = new Branding(brandingDTO.getProductId(), brandingDTO.getType(), brandingDTO.getName());
                        brandingEntity.setId(brandingDTO.getId());
                        brandingEntity.setCreated(brandingDTO.getCreated());
                        brandingEntity.setUpdated(brandingDTO.getUpdated());
                        branding.add(brandingEntity);
                    }
                }
                poolEntity.setBranding(branding);
            }
        }
        if (poolDTO.getProvidedProducts() != null) {
            if (poolDTO.getProvidedProducts().isEmpty()) {
                poolEntity.setProvidedProductDtos(Collections.emptySet());
            } else {
                Set<ProvidedProduct> providedProducts = new HashSet<>();
                for (PoolDTO.ProvidedProductDTO ppDTO : poolDTO.getProvidedProducts()) {
                    if (ppDTO != null) {
                        ProvidedProduct providedProduct = new ProvidedProduct();
                        providedProduct.setProductId(ppDTO.getProductId());
                        providedProduct.setProductName(ppDTO.getProductName());
                        providedProducts.add(providedProduct);
                    }
                }
                poolEntity.setProvidedProductDtos(providedProducts);
            }
        }
        if (poolDTO.getDerivedProvidedProducts() != null) {
            if (poolDTO.getDerivedProvidedProducts().isEmpty()) {
                poolEntity.setDerivedProvidedProductDtos(Collections.emptySet());
            } else {
                Set<ProvidedProduct> derivedProvidedProducts = new HashSet<>();
                for (PoolDTO.ProvidedProductDTO dppDTO : poolDTO.getDerivedProvidedProducts()) {
                    if (dppDTO != null) {
                        ProvidedProduct derivedProvidedProduct = new ProvidedProduct();
                        derivedProvidedProduct.setProductId(dppDTO.getProductId());
                        derivedProvidedProduct.setProductName(dppDTO.getProductName());
                        derivedProvidedProducts.add(derivedProvidedProduct);
                    }
                }
                poolEntity.setDerivedProvidedProductDtos(derivedProvidedProducts);
            }
        }
        entity.setPool(poolEntity);
    }
    if (dto.getCertificates() != null) {
        if (dto.getCertificates().isEmpty()) {
            entity.setCertificates(Collections.emptySet());
        } else {
            Set<EntitlementCertificate> entityCerts = new HashSet<>();
            for (CertificateDTO dtoCert : dto.getCertificates()) {
                if (dtoCert != null) {
                    EntitlementCertificate entityCert = new EntitlementCertificate();
                    entityCert.setId(dtoCert.getId());
                    entityCert.setKey(dtoCert.getKey());
                    entityCert.setCert(dtoCert.getCert());
                    entityCert.setCreated(dtoCert.getCreated());
                    entityCert.setUpdated(dtoCert.getUpdated());
                    if (dtoCert.getSerial() != null) {
                        CertificateSerialDTO dtoSerial = dtoCert.getSerial();
                        CertificateSerial entitySerial = new CertificateSerial();
                        entitySerial.setId(dtoSerial.getId());
                        entitySerial.setCollected(dtoSerial.isCollected());
                        entitySerial.setExpiration(dtoSerial.getExpiration());
                        entitySerial.setRevoked(dtoSerial.isRevoked());
                        entitySerial.setSerial(dtoSerial.getSerial() != null ? dtoSerial.getSerial().longValueExact() : null);
                        entitySerial.setCreated(dtoSerial.getCreated());
                        entitySerial.setUpdated(dtoSerial.getUpdated());
                        entityCert.setSerial(entitySerial);
                    }
                    entityCerts.add(entityCert);
                }
            }
            entity.setCertificates(entityCerts);
        }
    }
}
Also used : Owner(org.candlepin.model.Owner) EntitlementCertificate(org.candlepin.model.EntitlementCertificate) CertificateSerialDTO(org.candlepin.dto.manifest.v1.CertificateSerialDTO) PoolDTO(org.candlepin.dto.manifest.v1.PoolDTO) CertificateSerial(org.candlepin.model.CertificateSerial) Branding(org.candlepin.model.Branding) ProvidedProduct(org.candlepin.model.ProvidedProduct) CertificateDTO(org.candlepin.dto.manifest.v1.CertificateDTO) EntitlementDTO(org.candlepin.dto.manifest.v1.EntitlementDTO) BrandingDTO(org.candlepin.dto.manifest.v1.BrandingDTO) SourceStack(org.candlepin.model.SourceStack) Pool(org.candlepin.model.Pool) HashSet(java.util.HashSet)

Example 23 with PoolDTO

use of org.candlepin.dto.api.v1.PoolDTO in project candlepin by candlepin.

the class PoolResource method list.

/**
 * @deprecated Use the method on /owners
 * @return List of pools
 */
@ApiOperation(notes = "Retrieves a list of Pools @deprecated Use the method on /owners", value = "")
@ApiResponses({ @ApiResponse(code = 400, message = "if both consumer(unit) and owner are given, or if a" + " product id is specified without a consumer(unit) or owner"), @ApiResponse(code = 404, message = "if a specified consumer(unit) or owner is not found"), @ApiResponse(code = 403, message = "") })
@GET
@Produces(MediaType.APPLICATION_JSON)
@Wrapped(element = "pools")
@Deprecated
@SecurityHole
public List<PoolDTO> list(@QueryParam("owner") String ownerId, @QueryParam("consumer") String consumerUuid, @QueryParam("product") String productId, @ApiParam("Use with consumerUuid to list all pools available to the consumer. " + "This will include pools which would otherwise be omitted due to a rules" + " warning. (i.e. not recommended) Pools that trigger an error however will" + " still be omitted. (no entitlements available, consumer type mismatch, etc)") @QueryParam("listall") @DefaultValue("false") boolean listAll, @ApiParam("Uses ISO 8601 format") @QueryParam("activeon") String activeOn, @Context Principal principal, @Context PageRequest pageRequest) {
    // Make sure we were given sane query parameters:
    if (consumerUuid != null && ownerId != null) {
        throw new BadRequestException(i18n.tr("Cannot filter on both owner and unit"));
    }
    if (consumerUuid == null && ownerId == null && productId != null) {
        throw new BadRequestException(i18n.tr("A unit or owner is needed to filter on product"));
    }
    Date activeOnDate = activeOn != null ? ResourceDateParser.parseDateString(activeOn) : new Date();
    Consumer c = null;
    String oId = null;
    if (consumerUuid != null) {
        c = consumerCurator.findByUuid(consumerUuid);
        if (c == null) {
            throw new NotFoundException(i18n.tr("Unit: {0} not found", consumerUuid));
        }
        // Now that we have a consumer, check that this principal can access it:
        if (!principal.canAccess(c, SubResource.NONE, Access.READ_ONLY)) {
            throw new ForbiddenException(i18n.tr("User {0} cannot access unit {1}", principal.getPrincipalName(), consumerUuid));
        }
        if (listAll) {
            oId = c.getOwnerId();
        }
    }
    if (ownerId != null) {
        Owner o = ownerCurator.secureFind(ownerId);
        if (o == null) {
            throw new NotFoundException(i18n.tr("owner: {0}", ownerId));
        }
        oId = o.getId();
        // Now that we have an owner, check that this principal can access it:
        if (!principal.canAccess(o, SubResource.POOLS, Access.READ_ONLY)) {
            throw new ForbiddenException(i18n.tr("User {0} cannot access owner {1}", principal.getPrincipalName(), o.getKey()));
        }
    }
    // the system).
    if (consumerUuid == null && ownerId == null && !principal.hasFullAccess()) {
        throw new ForbiddenException(i18n.tr("User {0} cannot access all pools.", principal.getPrincipalName()));
    }
    Page<List<Pool>> page = poolManager.listAvailableEntitlementPools(c, null, oId, productId, null, activeOnDate, listAll, new PoolFilterBuilder(), pageRequest, false, false, null);
    List<Pool> poolList = page.getPageData();
    calculatedAttributesUtil.setCalculatedAttributes(poolList, activeOnDate);
    calculatedAttributesUtil.setQuantityAttributes(poolList, c, activeOnDate);
    // Store the page for the LinkHeaderResponseFilter
    ResteasyProviderFactory.pushContext(Page.class, page);
    List<PoolDTO> poolDTOs = new ArrayList<>();
    for (Pool pool : poolList) {
        poolDTOs.add(translator.translate(pool, PoolDTO.class));
    }
    return poolDTOs;
}
Also used : ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) Owner(org.candlepin.model.Owner) ArrayList(java.util.ArrayList) NotFoundException(org.candlepin.common.exceptions.NotFoundException) PoolDTO(org.candlepin.dto.api.v1.PoolDTO) Date(java.util.Date) Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) List(java.util.List) ArrayList(java.util.ArrayList) Pool(org.candlepin.model.Pool) SecurityHole(org.candlepin.common.auth.SecurityHole) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Wrapped(org.jboss.resteasy.annotations.providers.jaxb.Wrapped) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 24 with PoolDTO

use of org.candlepin.dto.api.v1.PoolDTO in project candlepin by candlepin.

the class AutobindRules method selectBestPools.

public List<PoolQuantity> selectBestPools(Consumer consumer, String[] productIds, List<Pool> pools, ComplianceStatus compliance, String serviceLevelOverride, Set<String> exemptLevels, boolean considerDerived) {
    List<PoolQuantity> bestPools = new ArrayList<>();
    int poolsBeforeContentFilter = pools.size();
    pools = filterPoolsForV1Certificates(consumer, pools);
    log.debug("pools.size() before V1 certificate filter: {}, after: {}", poolsBeforeContentFilter, pools.size());
    if (pools.size() == 0) {
        if (compliance.getReasons().size() == 0) {
            log.info("Consumer is compliant and does not require more entitlements.");
        } else {
            logProducts("No pools available to complete compliance for the set of products: {}" + " and consumer installed products: {}", productIds, consumer, false);
        }
        return bestPools;
    }
    if (log.isDebugEnabled()) {
        logProducts("Selecting best entitlement pool for products: {}" + "and consumer installed products: {}", productIds, consumer, true);
        if (poolsBeforeContentFilter != pools.size()) {
            log.debug("{} pools filtered due to too much content", (poolsBeforeContentFilter - pools.size()));
        }
    }
    List<PoolDTO> poolDTOs = new ArrayList<>();
    for (Pool pool : pools) {
        poolDTOs.add(this.translator.translate(pool, PoolDTO.class));
    }
    // Provide objects for the script:
    JsonJsContext args = new JsonJsContext(mapper);
    args.put("consumer", this.translator.translate(consumer, ConsumerDTO.class));
    Owner owner = ownerCurator.findOwnerById(consumer.getOwnerId());
    args.put("owner", this.translator.translate(owner, OwnerDTO.class));
    args.put("serviceLevelOverride", serviceLevelOverride);
    args.put("pools", poolDTOs.toArray());
    args.put("products", productIds);
    args.put("log", log, false);
    args.put("compliance", compliance);
    args.put("exemptList", exemptLevels);
    args.put("considerDerived", considerDerived);
    args.put("guestIds", consumer.getGuestIds());
    // Convert the JSON returned into a Map object:
    Map<String, Integer> result = null;
    try {
        String json = jsRules.invokeMethod(SELECT_POOL_FUNCTION, args);
        result = mapper.toObject(json, Map.class);
        if (log.isDebugEnabled()) {
            log.debug("Executed javascript rule: {}", SELECT_POOL_FUNCTION);
        }
    } catch (NoSuchMethodException e) {
        log.warn("No method found: {}", SELECT_POOL_FUNCTION);
        log.warn("Resorting to default pool selection behavior.");
        return selectBestPoolDefault(pools);
    } catch (RhinoException e) {
        throw new RuleExecutionException(e);
    }
    if (pools.size() > 0 && (result == null || result.isEmpty())) {
        logProducts("Rules did not select a pool for products: {} and consumer installed products: {}", productIds, consumer, false);
        return bestPools;
    }
    for (Pool p : pools) {
        for (Entry<String, Integer> entry : result.entrySet()) {
            if (p.getId().equals(entry.getKey())) {
                log.debug("Best pool: {}", p);
                int quantity = entry.getValue();
                bestPools.add(new PoolQuantity(p, quantity));
            }
        }
    }
    return bestPools;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Owner(org.candlepin.model.Owner) ArrayList(java.util.ArrayList) PoolDTO(org.candlepin.dto.rules.v1.PoolDTO) ConsumerDTO(org.candlepin.dto.rules.v1.ConsumerDTO) OwnerDTO(org.candlepin.dto.rules.v1.OwnerDTO) Pool(org.candlepin.model.Pool) JsonJsContext(org.candlepin.policy.js.JsonJsContext) RhinoException(org.mozilla.javascript.RhinoException) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException) Map(java.util.Map)

Aggregations

PoolDTO (org.candlepin.dto.api.v1.PoolDTO)19 Pool (org.candlepin.model.Pool)19 Test (org.junit.Test)16 Product (org.candlepin.model.Product)15 ConsumerPrincipal (org.candlepin.auth.ConsumerPrincipal)8 Principal (org.candlepin.auth.Principal)8 ArrayList (java.util.ArrayList)5 Date (java.util.Date)5 UserPrincipal (org.candlepin.auth.UserPrincipal)5 HashSet (java.util.HashSet)3 Map (java.util.Map)3 ConsumerDTO (org.candlepin.dto.rules.v1.ConsumerDTO)3 PoolDTO (org.candlepin.dto.rules.v1.PoolDTO)3 Branding (org.candlepin.model.Branding)3 Consumer (org.candlepin.model.Consumer)3 Owner (org.candlepin.model.Owner)3 JsonJsContext (org.candlepin.policy.js.JsonJsContext)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 ApiOperation (io.swagger.annotations.ApiOperation)2 ApiResponses (io.swagger.annotations.ApiResponses)2