Search in sources :

Example 16 with Page

use of org.candlepin.common.paging.Page in project candlepin by candlepin.

the class OwnerResourceTest method getAllEntitlementsForOwner.

@Test
public void getAllEntitlementsForOwner() {
    PageRequest req = new PageRequest();
    req.setPage(1);
    req.setPerPage(10);
    Owner owner = this.createOwner();
    Consumer consumer = this.createConsumer(owner);
    Pool pool = this.createPool(owner, this.createProduct());
    Entitlement e = this.createEntitlement(owner, consumer, pool, null);
    List<Entitlement> entitlements = new ArrayList<>();
    entitlements.add(e);
    Page<List<Entitlement>> page = new Page<>();
    page.setPageData(entitlements);
    OwnerResource ownerres = new OwnerResource(this.ownerCurator, this.productCurator, null, null, i18n, null, null, null, null, null, null, null, null, null, null, null, null, this.entitlementCurator, null, null, null, null, null, null, null, null, null, null, null, this.modelTranslator);
    List<EntitlementDTO> result = ownerres.ownerEntitlements(owner.getKey(), null, null, null, req);
    assertEquals(1, result.size());
    assertEquals(e.getId(), result.get(0).getId());
}
Also used : Owner(org.candlepin.model.Owner) ArrayList(java.util.ArrayList) Page(org.candlepin.common.paging.Page) PageRequest(org.candlepin.common.paging.PageRequest) EntitlementDTO(org.candlepin.dto.api.v1.EntitlementDTO) UpstreamConsumer(org.candlepin.model.UpstreamConsumer) Consumer(org.candlepin.model.Consumer) Pool(org.candlepin.model.Pool) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Entitlement(org.candlepin.model.Entitlement) Test(org.junit.Test)

Example 17 with Page

use of org.candlepin.common.paging.Page in project candlepin by candlepin.

the class PoolManagerTest method testEntitleByProductsEmptyArray.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testEntitleByProductsEmptyArray() throws Exception {
    Product product = TestUtil.createProduct();
    List<Pool> pools = new ArrayList<>();
    Pool pool1 = TestUtil.createPool(product);
    pools.add(pool1);
    Date now = new Date();
    ValidationResult result = mock(ValidationResult.class);
    // Setup an installed product for the consumer, we'll make the bind request
    // with no products specified, so this should get used instead:
    String[] installedPids = new String[] { product.getUuid() };
    ComplianceStatus mockCompliance = new ComplianceStatus(now);
    mockCompliance.addNonCompliantProduct(installedPids[0]);
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class))).thenReturn(mockCompliance);
    Page page = mock(Page.class);
    when(page.getPageData()).thenReturn(pools);
    when(mockPoolCurator.listAvailableEntitlementPools(any(Consumer.class), any(String.class), anyString(), anyString(), eq(now), any(PoolFilterBuilder.class), any(PageRequest.class), anyBoolean(), anyBoolean(), anyBoolean(), any(Date.class))).thenReturn(page);
    CandlepinQuery mockQuery = mock(CandlepinQuery.class);
    when(mockPoolCurator.listAllByIds(any(List.class))).thenReturn(mockQuery);
    when(mockQuery.iterator()).thenReturn(Arrays.asList(pool1).listIterator());
    when(enforcerMock.preEntitlement(any(Consumer.class), any(Pool.class), anyInt(), any(CallerType.class))).thenReturn(result);
    when(result.isSuccessful()).thenReturn(true);
    List<PoolQuantity> bestPools = new ArrayList<>();
    bestPools.add(new PoolQuantity(pool1, 1));
    when(autobindRules.selectBestPools(any(Consumer.class), any(String[].class), any(List.class), any(ComplianceStatus.class), any(String.class), any(Set.class), eq(false))).thenReturn(bestPools);
    // Make the call but provide a null array of product IDs (simulates healing):
    ConsumerType ctype = this.mockConsumerType(TestUtil.createConsumerType());
    Consumer consumer = TestUtil.createConsumer(ctype, owner);
    AutobindData data = AutobindData.create(consumer, owner).on(now);
    manager.entitleByProducts(data);
    verify(autobindRules).selectBestPools(any(Consumer.class), eq(installedPids), any(List.class), eq(mockCompliance), any(String.class), any(Set.class), eq(false));
}
Also used : PoolQuantity(org.candlepin.model.PoolQuantity) Set(java.util.Set) HashSet(java.util.HashSet) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) ArrayList(java.util.ArrayList) ConsumerInstalledProduct(org.candlepin.model.ConsumerInstalledProduct) Product(org.candlepin.model.Product) Page(org.candlepin.common.paging.Page) CandlepinQuery(org.candlepin.model.CandlepinQuery) Matchers.anyString(org.mockito.Matchers.anyString) CallerType(org.candlepin.policy.js.entitlement.Enforcer.CallerType) ValidationResult(org.candlepin.policy.ValidationResult) Date(java.util.Date) PageRequest(org.candlepin.common.paging.PageRequest) Consumer(org.candlepin.model.Consumer) PoolFilterBuilder(org.candlepin.model.PoolFilterBuilder) Pool(org.candlepin.model.Pool) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Matchers.anyList(org.mockito.Matchers.anyList) AutobindData(org.candlepin.resource.dto.AutobindData) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) ConsumerType(org.candlepin.model.ConsumerType) Test(org.junit.Test)

Example 18 with Page

use of org.candlepin.common.paging.Page in project candlepin by candlepin.

the class AbstractHibernateCurator method listAll.

@SuppressWarnings("unchecked")
@Transactional
public Page<List<E>> listAll(PageRequest pageRequest) {
    Page<List<E>> page = new Page<>();
    if (pageRequest != null) {
        Criteria count = createSecureCriteria();
        page.setMaxRecords(findRowCount(count));
        Criteria c = createSecureCriteria();
        page.setPageData(loadPageData(c, pageRequest));
        page.setPageRequest(pageRequest);
    } else {
        List<E> pageData = this.listAll().list();
        page.setMaxRecords(pageData.size());
        page.setPageData(pageData);
    }
    return page;
}
Also used : List(java.util.List) ArrayList(java.util.ArrayList) Page(org.candlepin.common.paging.Page) Criteria(org.hibernate.Criteria) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) Transactional(com.google.inject.persist.Transactional)

Example 19 with Page

use of org.candlepin.common.paging.Page in project candlepin by candlepin.

the class PoolCurator method listAvailableEntitlementPools.

/**
 * List entitlement pools.
 *
 * Pools will be refreshed from the underlying subscription service.
 *
 * @param consumer Consumer being entitled.
 * @param ownerId Owner whose subscriptions should be inspected.
 * @param productIds only entitlements which provide these products are included.
 * @param activeOn Indicates to return only pools valid on this date.
 *        Set to null for no date filtering.
 * @param filters filter builder with set filters to apply to the criteria.
 * @param pageRequest used to specify paging criteria.
 * @param postFilter if you plan on filtering the list in java
 * @return List of entitlement pools.
 */
@Transactional
@SuppressWarnings({ "unchecked", "checkstyle:indentation", "checkstyle:methodlength" })
public // TODO: Remove the methodlength suppression once this method is cleaned up
Page<List<Pool>> listAvailableEntitlementPools(Consumer consumer, String ownerId, Collection<String> productIds, String subscriptionId, Date activeOn, PoolFilterBuilder filters, PageRequest pageRequest, boolean postFilter, boolean addFuture, boolean onlyFuture, Date after) {
    if (log.isDebugEnabled()) {
        log.debug("Listing available pools for:");
        log.debug("    consumer: {}", consumer);
        log.debug("    owner: {}", ownerId);
        log.debug("    products: {}", productIds);
        log.debug("    subscription: {}", subscriptionId);
        log.debug("    active on: {}", activeOn);
        log.debug("    after: {}", after);
    }
    boolean joinedProvided = false;
    Criteria criteria = this.createSecureCriteria("Pool").createAlias("product", "Product").setProjection(Projections.distinct(Projections.id()));
    if (consumer != null) {
        if (ownerId != null && !ownerId.equals(consumer.getOwnerId())) {
            // Both a consumer and an owner were specified, but the consumer belongs to a different owner.
            // We can't possibly match a pool on two owners, so we can just abort immediately with an
            // empty page
            log.warn("Attempting to filter entitlement pools by owner and a consumer belonging to a " + "different owner: {}, {}", ownerId, consumer);
            Page<List<Pool>> output = new Page<>();
            output.setPageData(Collections.<Pool>emptyList());
            output.setMaxRecords(0);
            return output;
        }
        // We'll set the owner restriction later
        ownerId = consumer.getOwnerId();
        ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
        if (ctype.isManifest()) {
            DetachedCriteria hostPoolSubquery = DetachedCriteria.forClass(Pool.class, "PoolI").createAlias("PoolI.attributes", "attrib").setProjection(Projections.id()).add(Property.forName("Pool.id").eqProperty("PoolI.id")).add(Restrictions.eq("attrib.indices", Pool.Attributes.REQUIRES_HOST));
            criteria.add(Subqueries.notExists(hostPoolSubquery));
        } else if (!consumer.isGuest()) {
            criteria.add(Restrictions.not(this.addAttributeFilterSubquery(Pool.Attributes.VIRT_ONLY, Arrays.asList("true"))));
        } else if (consumer.hasFact("virt.uuid")) {
            Consumer host = this.consumerCurator.getHost(consumer);
            // Impl note:
            // This query matches pools with the "requires_host" attribute explicitly set to a
            // value other than the host we're looking for. We then negate the results of this
            // subquery, so our final result is: fetch pools which do not have a required host
            // or have a required host equal to our host.
            // TODO: If we don't have a host, should this be filtering at all? Seems strange to
            // be filtering pools which have a null/empty required host value. Probably just
            // wasted cycles.
            DetachedCriteria hostPoolSubquery = DetachedCriteria.forClass(Pool.class, "PoolI").createAlias("PoolI.attributes", "attrib").setProjection(Projections.id()).add(Property.forName("Pool.id").eqProperty("PoolI.id")).add(Restrictions.eq("attrib.indices", Pool.Attributes.REQUIRES_HOST)).add(Restrictions.ne("attrib.elements", host != null ? host.getUuid() : "").ignoreCase());
            criteria.add(Subqueries.notExists(hostPoolSubquery));
        }
    }
    if (ownerId != null) {
        criteria.add(Restrictions.eq("Pool.owner.id", ownerId));
    }
    if (activeOn != null) {
        if (onlyFuture) {
            criteria.add(Restrictions.ge("Pool.startDate", activeOn));
        } else if (!addFuture) {
            criteria.add(Restrictions.le("Pool.startDate", activeOn));
            criteria.add(Restrictions.ge("Pool.endDate", activeOn));
        } else {
            criteria.add(Restrictions.ge("Pool.endDate", activeOn));
        }
    }
    if (after != null) {
        criteria.add(Restrictions.gt("Pool.startDate", after));
    }
    // TODO: This section is sloppy. If we're going to clobber the bits in the filter with our own input
    // parameters, why bother accepting a filter to begin with? Similarly, why bother accepting a filter
    // if the method takes the arguments directly? If we're going to abstract out the filtering bits, we
    // should go all-in, cut down on the massive argument list and simply take a single filter object. -C
    // Subscription ID filter
    String value = subscriptionId == null && filters != null ? filters.getSubscriptionIdFilter() : subscriptionId;
    if (value != null && !value.isEmpty()) {
        criteria.createAlias("Pool.sourceSubscription", "srcsub").add(Restrictions.eq("srcsub.subscriptionId", value));
    }
    // Product ID filters
    Collection<String> values = productIds == null && filters != null ? filters.getProductIdFilter() : productIds;
    if (values != null && !values.isEmpty()) {
        if (!joinedProvided) {
            criteria.createAlias("Pool.providedProducts", "Provided", JoinType.LEFT_OUTER_JOIN);
            joinedProvided = true;
        }
        criteria.add(Restrictions.or(CPRestrictions.in("Product.id", values), CPRestrictions.in("Provided.id", values)));
    }
    if (filters != null) {
        // Pool ID filters
        values = filters.getIdFilters();
        if (values != null && !values.isEmpty()) {
            criteria.add(CPRestrictions.in("Pool.id", values));
        }
        // Matches stuff
        values = filters.getMatchesFilters();
        if (values != null && !values.isEmpty()) {
            if (!joinedProvided) {
                // This was an inner join -- might end up being important later
                criteria.createAlias("Pool.providedProducts", "Provided", JoinType.LEFT_OUTER_JOIN);
                joinedProvided = true;
            }
            criteria.createAlias("Provided.productContent", "PPC", JoinType.LEFT_OUTER_JOIN);
            criteria.createAlias("PPC.content", "Content", JoinType.LEFT_OUTER_JOIN);
            for (String matches : values) {
                String sanitized = this.sanitizeMatchesFilter(matches);
                Disjunction matchesDisjunction = Restrictions.disjunction();
                matchesDisjunction.add(CPRestrictions.ilike("Pool.contractNumber", sanitized, '!')).add(CPRestrictions.ilike("Pool.orderNumber", sanitized, '!')).add(CPRestrictions.ilike("Product.id", sanitized, '!')).add(CPRestrictions.ilike("Product.name", sanitized, '!')).add(CPRestrictions.ilike("Provided.id", sanitized, '!')).add(CPRestrictions.ilike("Provided.name", sanitized, '!')).add(CPRestrictions.ilike("Content.name", sanitized, '!')).add(CPRestrictions.ilike("Content.label", sanitized, '!')).add(this.addProductAttributeFilterSubquery(Product.Attributes.SUPPORT_LEVEL, Arrays.asList(matches)));
                criteria.add(matchesDisjunction);
            }
        }
        // Attribute filters
        for (Map.Entry<String, List<String>> entry : filters.getAttributeFilters().entrySet()) {
            String attrib = entry.getKey();
            values = entry.getValue();
            if (attrib != null && !attrib.isEmpty()) {
                if (values != null && !values.isEmpty()) {
                    List<String> positives = new LinkedList<>();
                    List<String> negatives = new LinkedList<>();
                    for (String attrValue : values) {
                        if (attrValue.startsWith("!")) {
                            negatives.add(attrValue.substring(1));
                        } else {
                            positives.add(attrValue);
                        }
                    }
                    if (!positives.isEmpty()) {
                        criteria.add(this.addAttributeFilterSubquery(attrib, positives));
                    }
                    if (!negatives.isEmpty()) {
                        criteria.add(Restrictions.not(this.addAttributeFilterSubquery(attrib, negatives)));
                    }
                } else {
                    criteria.add(this.addAttributeFilterSubquery(attrib, values));
                }
            }
        }
    }
    // Impl note:
    // Hibernate has an issue with properly hydrating objects within collections of the pool
    // when only a subset of the collection matches the criteria. To work around this, we pull
    // the ID list from the main filtering query, then pull the pools again using the ID list.
    // This also makes it easier to eventually start using a cursor, since the distinct entity
    // functionality doesn't work with cursors.
    List<String> poolIds = criteria.list();
    if (poolIds != null && !poolIds.isEmpty()) {
        criteria = this.currentSession().createCriteria(Pool.class).add(CPRestrictions.in("id", poolIds));
        return this.listByCriteria(criteria, pageRequest, postFilter);
    }
    Page<List<Pool>> output = new Page<>();
    output.setPageData(Collections.<Pool>emptyList());
    output.setMaxRecords(0);
    return output;
}
Also used : DetachedCriteria(org.hibernate.criterion.DetachedCriteria) Page(org.candlepin.common.paging.Page) Criteria(org.hibernate.Criteria) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) LinkedList(java.util.LinkedList) Disjunction(org.hibernate.criterion.Disjunction) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ActivationKeyPool(org.candlepin.model.activationkeys.ActivationKeyPool) HashMap(java.util.HashMap) Map(java.util.Map) Transactional(com.google.inject.persist.Transactional)

Example 20 with Page

use of org.candlepin.common.paging.Page in project candlepin by candlepin.

the class EntitlementResourceTest method getAllEntitlementsForConsumer.

@Test
public void getAllEntitlementsForConsumer() {
    PageRequest req = new PageRequest();
    req.setPage(1);
    req.setPerPage(10);
    Owner owner = TestUtil.createOwner();
    Consumer consumer = TestUtil.createConsumer(owner);
    Pool pool = TestUtil.createPool(owner, TestUtil.createProduct());
    Entitlement e = TestUtil.createEntitlement(owner, consumer, pool, null);
    e.setId("getAllEntitlementsForConsumer");
    List<Entitlement> entitlements = new ArrayList<>();
    entitlements.add(e);
    Page<List<Entitlement>> page = new Page<>();
    page.setPageData(entitlements);
    EntitlementDTO entitlementDTO = new EntitlementDTO();
    entitlementDTO.setId("getAllEntitlementsForConsumer");
    when(consumerCurator.findByUuid(eq(consumer.getUuid()))).thenReturn(consumer);
    when(entitlementCurator.listByConsumer(isA(Consumer.class), anyString(), isA(EntitlementFilterBuilder.class), isA(PageRequest.class))).thenReturn(page);
    when(modelTranslator.translate(isA(Entitlement.class), eq(EntitlementDTO.class))).thenReturn(entitlementDTO);
    List<EntitlementDTO> result = entResource.listAllForConsumer(consumer.getUuid(), null, null, req);
    assertEquals(1, result.size());
    assertEquals("getAllEntitlementsForConsumer", result.get(0).getId());
}
Also used : Owner(org.candlepin.model.Owner) EntitlementFilterBuilder(org.candlepin.model.EntitlementFilterBuilder) ArrayList(java.util.ArrayList) Page(org.candlepin.common.paging.Page) PageRequest(org.candlepin.common.paging.PageRequest) EntitlementDTO(org.candlepin.dto.api.v1.EntitlementDTO) Consumer(org.candlepin.model.Consumer) Pool(org.candlepin.model.Pool) ArrayList(java.util.ArrayList) List(java.util.List) Entitlement(org.candlepin.model.Entitlement) Test(org.junit.Test)

Aggregations

Page (org.candlepin.common.paging.Page)20 PageRequest (org.candlepin.common.paging.PageRequest)16 Test (org.junit.Test)14 ArrayList (java.util.ArrayList)10 List (java.util.List)10 LinkedList (java.util.LinkedList)6 Consumer (org.candlepin.model.Consumer)6 Entitlement (org.candlepin.model.Entitlement)6 Pool (org.candlepin.model.Pool)6 CandlepinQuery (org.candlepin.model.CandlepinQuery)5 Transactional (com.google.inject.persist.Transactional)4 Date (java.util.Date)4 HashSet (java.util.HashSet)4 Set (java.util.Set)4 EntitlementDTO (org.candlepin.dto.api.v1.EntitlementDTO)4 PoolFilterBuilder (org.candlepin.model.PoolFilterBuilder)4 Product (org.candlepin.model.Product)4 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)3 ConsumerType (org.candlepin.model.ConsumerType)3 EntitlementFilterBuilder (org.candlepin.model.EntitlementFilterBuilder)3