Search in sources :

Example 6 with PoolFilterBuilder

use of org.candlepin.model.PoolFilterBuilder in project candlepin by candlepin.

the class OwnerResource method listPools.

/**
 * Retrieves a list of Pools for an Owner
 *
 * @param ownerKey id of the owner whose entitlement pools are sought.
 * @param matches Find pools matching the given pattern in a variety of fields.
 * * and ? wildcards are supported.
 * @return a list of Pool objects
 * @httpcode 400
 * @httpcode 404
 * @httpcode 200
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{owner_key}/pools")
@SuppressWarnings("checkstyle:indentation")
@ApiOperation(notes = "Retrieves a list of Pools for an Owner", value = "List Pools")
@ApiResponses({ @ApiResponse(code = 404, message = "Owner not found"), @ApiResponse(code = 400, message = "Invalid request") })
public List<PoolDTO> listPools(@PathParam("owner_key") @Verify(value = Owner.class, subResource = SubResource.POOLS) String ownerKey, @QueryParam("consumer") String consumerUuid, @QueryParam("activation_key") String activationKeyName, @QueryParam("product") String productId, @QueryParam("subscription") String subscriptionId, @ApiParam("Include pools that are not suited to the unit's facts.") @QueryParam("listall") @DefaultValue("false") boolean listAll, @ApiParam("Date to use as current time for lookup criteria. Defaults" + " to current date if not specified.") @QueryParam("activeon") @DefaultValue(DateFormat.NOW) @DateFormat Date activeOn, @ApiParam("Find pools matching the given pattern in a variety of fields;" + " * and ? wildcards are supported; may be specified multiple times") @QueryParam("matches") List<String> matches, @ApiParam("The attributes to return based on the specified types.") @QueryParam("attribute") @CandlepinParam(type = KeyValueParameter.class) List<KeyValueParameter> attrFilters, @ApiParam("When set to true, it will add future dated pools to the result, " + "based on the activeon date.") @QueryParam("add_future") @DefaultValue("false") boolean addFuture, @ApiParam("When set to true, it will return only future dated pools to the result, " + "based on the activeon date.") @QueryParam("only_future") @DefaultValue("false") boolean onlyFuture, @ApiParam("Will only return pools with a start date after the supplied date. " + "Overrides the activeOn date.") @QueryParam("after") @DateFormat Date after, @ApiParam("One or more pool IDs to use to filter the output; only pools with IDs matching " + "those provided will be returned; may be specified multiple times") @QueryParam("poolid") List<String> poolIds, @Context Principal principal, @Context PageRequest pageRequest) {
    Owner owner = findOwnerByKey(ownerKey);
    Consumer c = null;
    if (consumerUuid != null) {
        c = consumerCurator.findByUuid(consumerUuid);
        if (c == null) {
            throw new NotFoundException(i18n.tr("Unit: {0} not found", consumerUuid));
        }
        if (!c.getOwnerId().equals(owner.getId())) {
            throw new BadRequestException("Consumer specified does not belong to owner on path");
        }
        if (!principal.canAccess(c, SubResource.NONE, Access.READ_ONLY)) {
            throw new ForbiddenException(i18n.tr("User {0} cannot access consumer {1}", principal.getPrincipalName(), c.getUuid()));
        }
    }
    ActivationKey key = null;
    if (activationKeyName != null) {
        key = activationKeyCurator.lookupForOwner(activationKeyName, owner);
        if (key == null) {
            throw new BadRequestException(i18n.tr("ActivationKey with id {0} could not be found.", activationKeyName));
        }
    }
    if (addFuture && onlyFuture) {
        throw new BadRequestException(i18n.tr("The flags add_future and only_future cannot be used at the same time."));
    }
    if (after != null && (addFuture || onlyFuture)) {
        throw new BadRequestException(i18n.tr("The flags add_future and only_future cannot be used with the parameter after."));
    }
    if (after != null) {
        activeOn = null;
    }
    // Process the filters passed for the attributes
    PoolFilterBuilder poolFilters = new PoolFilterBuilder();
    for (KeyValueParameter filterParam : attrFilters) {
        poolFilters.addAttributeFilter(filterParam.key(), filterParam.value());
    }
    if (matches != null) {
        matches.stream().filter(elem -> elem != null && !elem.isEmpty()).forEach(elem -> poolFilters.addMatchesFilter(elem));
    }
    if (poolIds != null && !poolIds.isEmpty()) {
        poolFilters.addIdFilters(poolIds);
    }
    Page<List<Pool>> page = poolManager.listAvailableEntitlementPools(c, key, owner.getId(), productId, subscriptionId, activeOn, listAll, poolFilters, pageRequest, addFuture, onlyFuture, after);
    List<Pool> poolList = page.getPageData();
    calculatedAttributesUtil.setCalculatedAttributes(poolList, activeOn);
    calculatedAttributesUtil.setQuantityAttributes(poolList, c, activeOn);
    // 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 : StringUtils(org.apache.commons.lang.StringUtils) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) ApiParam(io.swagger.annotations.ApiParam) CalculatedAttributesUtil(org.candlepin.resource.util.CalculatedAttributesUtil) EventSink(org.candlepin.audit.EventSink) MediaType(javax.ws.rs.core.MediaType) ImportRecordCurator(org.candlepin.model.ImportRecordCurator) PageRequest(org.candlepin.common.paging.PageRequest) ImporterException(org.candlepin.sync.ImporterException) ExporterMetadataCurator(org.candlepin.model.ExporterMetadataCurator) ActivationKeyCurator(org.candlepin.model.activationkeys.ActivationKeyCurator) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) DateFormat(org.candlepin.resteasy.DateFormat) HealEntireOrgJob(org.candlepin.pinsetter.tasks.HealEntireOrgJob) EventCurator(org.candlepin.model.EventCurator) Feed(org.jboss.resteasy.plugins.providers.atom.Feed) ActivationKeyDTO(org.candlepin.dto.api.v1.ActivationKeyDTO) SyncDataFormatException(org.candlepin.sync.SyncDataFormatException) ResourceMovedException(org.candlepin.common.exceptions.ResourceMovedException) UeberCertificateCurator(org.candlepin.model.UeberCertificateCurator) Set(java.util.Set) PoolManager(org.candlepin.controller.PoolManager) Access(org.candlepin.auth.Access) IseException(org.candlepin.common.exceptions.IseException) Type(org.candlepin.audit.Event.Type) OwnerServiceAdapter(org.candlepin.service.OwnerServiceAdapter) PoolDTO(org.candlepin.dto.api.v1.PoolDTO) Util(org.candlepin.util.Util) I18n(org.xnap.commons.i18n.I18n) Event(org.candlepin.audit.Event) Subscription(org.candlepin.model.dto.Subscription) GET(javax.ws.rs.GET) RefreshPoolsJob(org.candlepin.pinsetter.tasks.RefreshPoolsJob) KeyValueParameter(org.candlepin.resteasy.parameter.KeyValueParameter) ContentAccessCertServiceAdapter(org.candlepin.service.ContentAccessCertServiceAdapter) EventDTO(org.candlepin.dto.api.v1.EventDTO) ArrayList(java.util.ArrayList) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) Target(org.candlepin.audit.Event.Target) Entitlement(org.candlepin.model.Entitlement) StringTokenizer(java.util.StringTokenizer) Branding(org.candlepin.model.Branding) Api(io.swagger.annotations.Api) UpstreamConsumerDTO(org.candlepin.dto.api.v1.UpstreamConsumerDTO) UeberCertificateGenerator(org.candlepin.model.UeberCertificateGenerator) CandlepinException(org.candlepin.common.exceptions.CandlepinException) OwnerInfo(org.candlepin.model.OwnerInfo) ModelTranslator(org.candlepin.dto.ModelTranslator) ExporterMetadata(org.candlepin.model.ExporterMetadata) ServiceLevelValidator(org.candlepin.util.ServiceLevelValidator) Wrapped(org.jboss.resteasy.annotations.providers.jaxb.Wrapped) IOException(java.io.IOException) CandlepinQuery(org.candlepin.model.CandlepinQuery) File(java.io.File) EntitlementCurator(org.candlepin.model.EntitlementCurator) UndoImportsJob(org.candlepin.pinsetter.tasks.UndoImportsJob) CandlepinParam(org.candlepin.resteasy.parameter.CandlepinParam) ApiResponse(io.swagger.annotations.ApiResponse) ImportRecord(org.candlepin.model.ImportRecord) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) EnvironmentDTO(org.candlepin.dto.api.v1.EnvironmentDTO) Date(java.util.Date) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) MultipartInput(org.jboss.resteasy.plugins.providers.multipart.MultipartInput) EntitlementFinderUtil(org.candlepin.resource.util.EntitlementFinderUtil) EntitlementFilterBuilder(org.candlepin.model.EntitlementFilterBuilder) ConflictOverrides(org.candlepin.sync.ConflictOverrides) ActivationKeyContentOverride(org.candlepin.model.activationkeys.ActivationKeyContentOverride) Transactional(com.google.inject.persist.Transactional) OwnerDTO(org.candlepin.dto.api.v1.OwnerDTO) ConflictException(org.candlepin.common.exceptions.ConflictException) ApiOperation(io.swagger.annotations.ApiOperation) InputPart(org.jboss.resteasy.plugins.providers.multipart.InputPart) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ConsumerTypeCurator(org.candlepin.model.ConsumerTypeCurator) DefaultValue(javax.ws.rs.DefaultValue) ContentOverrideValidator(org.candlepin.util.ContentOverrideValidator) Product(org.candlepin.model.Product) DELETE(javax.ws.rs.DELETE) NotFoundException(org.candlepin.common.exceptions.NotFoundException) UpstreamConsumer(org.candlepin.model.UpstreamConsumer) Context(javax.ws.rs.core.Context) OwnerManager(org.candlepin.controller.OwnerManager) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) EventAdapter(org.candlepin.audit.EventAdapter) GenericType(org.jboss.resteasy.util.GenericType) Page(org.candlepin.common.paging.Page) OwnerCurator(org.candlepin.model.OwnerCurator) EntitlementDTO(org.candlepin.dto.api.v1.EntitlementDTO) OwnerProductCurator(org.candlepin.model.OwnerProductCurator) ManifestFileServiceException(org.candlepin.sync.file.ManifestFileServiceException) ConsumerCurator(org.candlepin.model.ConsumerCurator) List(java.util.List) PersistenceException(javax.persistence.PersistenceException) ProductCurator(org.candlepin.model.ProductCurator) SourceSubscription(org.candlepin.model.SourceSubscription) PathParam(javax.ws.rs.PathParam) ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) Release(org.candlepin.model.Release) Verify(org.candlepin.auth.Verify) ManifestManager(org.candlepin.controller.ManifestManager) ConsumerType(org.candlepin.model.ConsumerType) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) ApiResponses(io.swagger.annotations.ApiResponses) ConfigProperties(org.candlepin.config.ConfigProperties) Pool(org.candlepin.model.Pool) UeberCertificate(org.candlepin.model.UeberCertificate) HashSet(java.util.HashSet) SubResource(org.candlepin.auth.SubResource) PoolType(org.candlepin.model.Pool.PoolType) Owner(org.candlepin.model.Owner) CollectionUtils(org.apache.commons.collections.CollectionUtils) BadRequestException(org.candlepin.common.exceptions.BadRequestException) BrandingDTO(org.candlepin.dto.api.v1.BrandingDTO) Environment(org.candlepin.model.Environment) Principal(org.candlepin.auth.Principal) LinkedList(java.util.LinkedList) Configuration(org.candlepin.common.config.Configuration) JobDetail(org.quartz.JobDetail) OwnerInfoCurator(org.candlepin.model.OwnerInfoCurator) ResolverUtil(org.candlepin.resource.util.ResolverUtil) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) EnvironmentCurator(org.candlepin.model.EnvironmentCurator) ConsumerTypeValidator(org.candlepin.resource.util.ConsumerTypeValidator) EventFactory(org.candlepin.audit.EventFactory) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ImportJob(org.candlepin.pinsetter.tasks.ImportJob) Level(ch.qos.logback.classic.Level) EntitlementCertificateCurator(org.candlepin.model.EntitlementCertificateCurator) PUT(javax.ws.rs.PUT) Consumer(org.candlepin.model.Consumer) Authorization(io.swagger.annotations.Authorization) Collections(java.util.Collections) ArrayUtils(org.apache.commons.lang.ArrayUtils) Owner(org.candlepin.model.Owner) ForbiddenException(org.candlepin.common.exceptions.ForbiddenException) ArrayList(java.util.ArrayList) NotFoundException(org.candlepin.common.exceptions.NotFoundException) PoolDTO(org.candlepin.dto.api.v1.PoolDTO) ActivationKey(org.candlepin.model.activationkeys.ActivationKey) UpstreamConsumer(org.candlepin.model.UpstreamConsumer) Consumer(org.candlepin.model.Consumer) BadRequestException(org.candlepin.common.exceptions.BadRequestException) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) KeyValueParameter(org.candlepin.resteasy.parameter.KeyValueParameter) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Pool(org.candlepin.model.Pool) 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 7 with PoolFilterBuilder

use of org.candlepin.model.PoolFilterBuilder in project candlepin by candlepin.

the class CandlepinPoolManager method getBestPools.

@Override
public List<PoolQuantity> getBestPools(Consumer consumer, String[] productIds, Date entitleDate, String ownerId, String serviceLevelOverride, Collection<String> fromPools) throws EntitlementRefusedException {
    Map<String, ValidationResult> failedResults = new HashMap<>();
    Date activePoolDate = entitleDate;
    if (entitleDate == null) {
        activePoolDate = new Date();
    }
    PoolFilterBuilder poolFilter = new PoolFilterBuilder();
    poolFilter.addIdFilters(fromPools);
    List<Pool> allOwnerPools = this.listAvailableEntitlementPools(consumer, null, ownerId, null, null, activePoolDate, false, poolFilter, null, false, false, null).getPageData();
    List<Pool> filteredPools = new LinkedList<>();
    // We have to check compliance status here so we can replace an empty
    // array of product IDs with the array the consumer actually needs. (i.e. during
    // a healing request)
    ComplianceStatus compliance = complianceRules.getStatus(consumer, entitleDate, false);
    if (productIds == null || productIds.length == 0) {
        log.debug("No products specified for bind, checking compliance to see what is needed.");
        Set<String> tmpSet = new HashSet<>();
        tmpSet.addAll(compliance.getNonCompliantProducts());
        tmpSet.addAll(compliance.getPartiallyCompliantProducts().keySet());
        productIds = tmpSet.toArray(new String[] {});
    }
    if (log.isDebugEnabled()) {
        log.debug("Attempting for products on date: {}", entitleDate);
        for (String productId : productIds) {
            log.debug("  {}", productId);
        }
    }
    // Bulk fetch our provided product IDs so we're not hitting the DB several times
    // for this lookup.
    Map<String, Set<String>> providedProductIds = this.poolCurator.getProvidedProductIds(allOwnerPools);
    for (Pool pool : allOwnerPools) {
        boolean providesProduct = false;
        // We want to complete partial stacks if possible, even if they do not provide any products
        Product poolProduct = pool.getProduct();
        String stackingId = poolProduct.getAttributeValue(Product.Attributes.STACKING_ID);
        if (stackingId != null && compliance.getPartialStacks().containsKey(stackingId)) {
            providesProduct = true;
        } else {
            Set<String> poolProvidedProductIds = providedProductIds.get(pool.getId());
            String poolProductId = pool.getProduct() != null ? pool.getProduct().getId() : null;
            if (poolProductId != null) {
                // Add the base product to our list of "provided" products
                if (poolProvidedProductIds != null) {
                    poolProvidedProductIds.add(poolProductId);
                } else {
                    poolProvidedProductIds = Collections.singleton(poolProductId);
                }
            }
            if (poolProvidedProductIds != null) {
                for (String productId : productIds) {
                    if (poolProvidedProductIds.contains(productId)) {
                        providesProduct = true;
                        break;
                    }
                }
            }
        }
        if (providesProduct) {
            ValidationResult result = enforcer.preEntitlement(consumer, pool, 1, CallerType.BEST_POOLS);
            if (result.hasErrors() || result.hasWarnings()) {
                failedResults.put(pool.getId(), result);
                log.debug("Pool filtered from candidates due to rules failure: {}", pool.getId());
            } else {
                filteredPools.add(pool);
            }
        }
    }
    // Only throw refused exception if we actually hit the rules:
    if (filteredPools.size() == 0 && !failedResults.isEmpty()) {
        throw new EntitlementRefusedException(failedResults);
    }
    List<PoolQuantity> enforced = autobindRules.selectBestPools(consumer, productIds, filteredPools, compliance, serviceLevelOverride, poolCurator.retrieveServiceLevelsForOwner(ownerId, true), false);
    // Sort the resulting pools to avoid deadlocks
    Collections.sort(enforced);
    return enforced;
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) EntitlementRefusedException(org.candlepin.policy.EntitlementRefusedException) Product(org.candlepin.model.Product) ValidationResult(org.candlepin.policy.ValidationResult) Date(java.util.Date) LinkedList(java.util.LinkedList) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) Pool(org.candlepin.model.Pool) HashSet(java.util.HashSet)

Example 8 with PoolFilterBuilder

use of org.candlepin.model.PoolFilterBuilder in project candlepin by candlepin.

the class PoolManagerFunctionalTest method testListAllForConsumerIncludesWarnings.

@Test
public void testListAllForConsumerIncludesWarnings() {
    Page<List<Pool>> results = poolManager.listAvailableEntitlementPools(parentSystem, null, parentSystem.getOwnerId(), null, null, null, true, new PoolFilterBuilder(), new PageRequest(), false, false, null);
    assertEquals(4, results.getPageData().size());
    Pool pool = createPool(o, socketLimitedProduct, 100L, TestUtil.createDate(2000, 3, 2), TestUtil.createDate(2050, 3, 2));
    poolCurator.create(pool);
    parentSystem.setFact("cpu.sockets", "4");
    results = poolManager.listAvailableEntitlementPools(parentSystem, null, parentSystem.getOwnerId(), null, null, null, true, new PoolFilterBuilder(), new PageRequest(), false, false, null);
    // Expect the warnings to be included. Should have one more pool available.
    assertEquals(5, results.getPageData().size());
}
Also used : PageRequest(org.candlepin.common.paging.PageRequest) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Pool(org.candlepin.model.Pool) Test(org.junit.Test)

Example 9 with PoolFilterBuilder

use of org.candlepin.model.PoolFilterBuilder in project candlepin by candlepin.

the class PoolManagerFunctionalTest method testListAllForOldGuestExcludesTempPools.

@Test
public void testListAllForOldGuestExcludesTempPools() {
    Pool pool = createPool(o, virtGuest, 100L, TestUtil.createDate(2000, 3, 2), TestUtil.createDate(2050, 3, 2));
    pool.setAttribute(Pool.Attributes.UNMAPPED_GUESTS_ONLY, "true");
    poolCurator.create(pool);
    Page<List<Pool>> results = poolManager.listAvailableEntitlementPools(childVirtSystem, null, o.getId(), virtGuest.getId(), null, null, true, new PoolFilterBuilder(), new PageRequest(), false, false, null);
    int newbornPools = results.getPageData().size();
    childVirtSystem.setCreated(TestUtil.createDate(2000, 01, 01));
    consumerCurator.update(childVirtSystem);
    results = poolManager.listAvailableEntitlementPools(childVirtSystem, null, o.getId(), virtGuest.getId(), null, null, true, new PoolFilterBuilder(), new PageRequest(), false, false, null);
    assertEquals(newbornPools - 1, results.getPageData().size());
}
Also used : PageRequest(org.candlepin.common.paging.PageRequest) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) Pool(org.candlepin.model.Pool) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 10 with PoolFilterBuilder

use of org.candlepin.model.PoolFilterBuilder 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)

Aggregations

PoolFilterBuilder (org.candlepin.model.PoolFilterBuilder)11 LinkedList (java.util.LinkedList)10 Pool (org.candlepin.model.Pool)10 ArrayList (java.util.ArrayList)8 List (java.util.List)8 PageRequest (org.candlepin.common.paging.PageRequest)7 Test (org.junit.Test)6 Product (org.candlepin.model.Product)5 Date (java.util.Date)4 Consumer (org.candlepin.model.Consumer)4 HashSet (java.util.HashSet)3 Set (java.util.Set)3 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)3 Owner (org.candlepin.model.Owner)3 ApiOperation (io.swagger.annotations.ApiOperation)2 ApiResponses (io.swagger.annotations.ApiResponses)2 HashMap (java.util.HashMap)2 GET (javax.ws.rs.GET)2 Entitlement (org.candlepin.model.Entitlement)2 ActivationKey (org.candlepin.model.activationkeys.ActivationKey)2