Example usage for org.hibernate ScrollMode FORWARD_ONLY

List of usage examples for org.hibernate ScrollMode FORWARD_ONLY

Introduction

In this page you can find the example usage for org.hibernate ScrollMode FORWARD_ONLY.

Prototype

ScrollMode FORWARD_ONLY

To view the source code for org.hibernate ScrollMode FORWARD_ONLY.

Click Source Link

Document

Requests a scrollable result that is only scrollable forwards.

Usage

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots on the target date.
 *
 * @param targetDate//from ww w  . j ava  2 s. co m
 *  The date for which to retrieve compliance snapshots. If null, the current date will be used
 *  instead.
 *
 * @param consumerUuids
 *  A list of consumer UUIDs to use to filter the results. If provided, only compliances for
 *  consumers in the list will be retrieved.
 *
 * @param ownerFilters
 *  A list of owners to use to filter the results. If provided, only compliances for consumers
 *  belonging to the specified owners (orgs) will be retrieved.
 *
 * @param statusFilters
 *  A list of statuses to use to filter the results. If provided, only compliances with a status
 *  matching the list will be retrieved.
 *
 * @param productNameFilters
 *  A list of product names to use to filter compliances. If provided, only compliances for
 *  consumers having installed the specified products will be retrieved.
 *
 * @param subscriptionSkuFilters
 *  A list of subscription skus to use to filter compliances. If provided, only compliances for
 *  the specified subscription skus will be retrieved.
 *
 * @param subscriptionNameFilters
 *  A list of subscription names to use to filter compliances. If provided, only compliances for
 *  the specified subscription names will be retrieved.
 *
 * @param attributeFilters
 *  A map of entitlement attributes to use to filter compliances. If provided, only compliances
 *  for entitlements having the specified values for the given attributes will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the compliance snapshots for the target date and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids,
        List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters,
        List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters,
        Map<String, String> attributeFilters, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class);
    subquery.createAlias("consumer", "c");
    subquery.createAlias("c.consumerState", "state");

    // https://hibernate.atlassian.net/browse/HHH-2776
    if (consumerUuids != null && !consumerUuids.isEmpty()) {
        subquery.add(Restrictions.in("c.uuid", consumerUuids));
    }

    Date toCheck = targetDate == null ? new Date() : targetDate;
    subquery.add(
            Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck)));
    subquery.add(Restrictions.le("state.created", toCheck));

    if (ownerFilters != null && !ownerFilters.isEmpty()) {
        subquery.createAlias("c.owner", "o");
        subquery.add(Restrictions.in("o.key", ownerFilters));
    }

    subquery.add(Restrictions.le("date", toCheck));

    subquery.setProjection(
            Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid")));

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs")
            .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery))
            .setCacheMode(CacheMode.IGNORE).setReadOnly(true);

    if ((statusFilters != null && !statusFilters.isEmpty())
            || (attributeFilters != null && attributeFilters.containsKey("management_enabled"))
            || (productNameFilters != null && !productNameFilters.isEmpty())) {

        query.createAlias("comp.status", "stat");

        if (statusFilters != null && !statusFilters.isEmpty()) {
            query.add(Restrictions.in("stat.status", statusFilters));
        }

        if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) {
            boolean managementEnabledFilter = PropertyConverter
                    .toBoolean(attributeFilters.get("management_enabled"));
            query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter));
        }

        if (productNameFilters != null && !productNameFilters.isEmpty()) {
            query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN);

            DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2");
            prodQuery.createAlias("comp2.consumer", "cons2");
            prodQuery.createAlias("cons2.installedProducts", "installed");
            prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters),
                    Restrictions.eqProperty("comp2.id", "comp.id")));
            prodQuery.setProjection(Projections.property("installed.productId"));

            query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery),
                    Property.forName("pcprod.productId").in(prodQuery),
                    Property.forName("ncprod.productId").in(prodQuery)));
        }
    }

    // Add subscription filters, if necessary
    if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty())
            || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) {

        // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy
        // to errorneously truncate "long" ones. Actual property/field names are safe, though.
        query.createAlias("comp.entitlements", "entsnap");

        if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters));
        }

        if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters));
        }
    }

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots for the specified consumer.
 *
 * @param consumerUUID//  w  w  w  .j  a v a 2 s .co m
 *  The UUID for the consumer for which to retrieve compliance snapshots.
 *
 * @param startDate
 *  The start date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  after the start date, and the snapshot immediately preceding it, will be retrieved.
 *
 * @param endDate
 *  The end date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  before the end date will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the snapshots for the specified consumer, and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate,
        Date endDate, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp1");
    query.createAlias("comp1.consumer", "cons1");

    query.add(Restrictions.eq("cons1.uuid", consumerUUID));

    if (startDate != null) {
        DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2");
        subquery.createAlias("comp2.consumer", "cons2");
        subquery.createAlias("cons2.consumerState", "state2");

        subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"),
                Restrictions.gt("state2.deleted", startDate)));

        subquery.add(Restrictions.lt("state2.created", startDate));
        subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid"));
        subquery.add(Restrictions.lt("comp2.date", startDate));

        subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date")));

        query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate))
                .add(Subqueries.propertyEq("comp1.date", subquery)));
    }

    if (endDate != null) {
        query.add(Restrictions.le("comp1.date", endDate));
    }

    query.setCacheMode(CacheMode.IGNORE);
    query.setReadOnly(true);

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves the compliance status counts over the given time span with the specified criteria.
 * The counts are returned in a map of maps, with the outer map mapping the dates to the inner
 * map which maps the statuses to their respective counts.
 * <p></p>/*from ww w  .  j  a  v  a2s .  c o  m*/
 * If the start and/or end dates are null, the time span will be similarly unrestricted. Note
 * that the time within a given Date object is ignored. If neither the start nor end dates are
 * provided, all known compliance status data will be used.
 *
 * @param startDate
 *  The date at which the time span should begin. If null, all compliance statuses before the
 *  end date (if provided) will be used.
 *
 * @param endDate
 *  The date at which the time span should end. If null, all compliance statuses after the
 *  start date (if provided) will be used.
 *
 * @param sku
 *  A subscription sku to use to filter compliance status counts. If provided, only consumers
 *  using the specified sku will be counted.
 *
 * @param subscriptionName
 *  A subscription name to use to filter compliance status counts. If provided, only consumers
 *  using subscriptions with the specified product name will be counted.
 *
 * @param productName
 *  A product name to use to filter compliance status counts. If provided, only consumers with
 *  an installed product with the specified product name will be counted.
 *
 * @param attributes
 *  A map of entitlement attributes to use to filter compliance status counts. If provided, only
 *  consumers with entitlements having the specified values for the given attributes will be
 *  counted.
 *
 * @param ownerKey
 *  An owner key to use to filter compliance status counts. If provided, only consumers
 *  associated with the specified owner key/account will be counted.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A page containing a map of maps containing the compliance status counts, grouped by day. If
 *  no counts were found for the given time span, the page will contain an empty map.
 */
public Page<Map<Date, Map<String, Integer>>> getComplianceStatusCounts(Date startDate, Date endDate,
        String ownerKey, List<String> consumerUuids, String sku, String subscriptionName, String productName,
        Map<String, String> attributes, PageRequest pageRequest) {

    Page<Map<Date, Map<String, Integer>>> page = new Page<Map<Date, Map<String, Integer>>>();
    page.setPageRequest(pageRequest);

    // Build our query...
    // Impl note: This query's results MUST be sorted by date in ascending order. If it's not,
    // the algorithm below breaks.
    Query query = this.buildComplianceStatusCountQuery(this.currentSession(), startDate, endDate, ownerKey,
            consumerUuids, sku, subscriptionName, productName, attributes);

    // Clamp our dates so they're no further out than "today."
    Date today = new Date();
    if (startDate != null && startDate.after(today)) {
        startDate = today;
    }

    if (endDate != null && endDate.after(today)) {
        endDate = today;
    }

    // Execute & process results...
    Map<Date, Map<String, Integer>> resultmap = new TreeMap<Date, Map<String, Integer>>();
    Map<String, Object[]> cstatusmap = new HashMap<String, Object[]>();

    // Step through our data and do our manual aggregation bits...
    ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);

    if (results.next()) {
        Calendar date = Calendar.getInstance();

        Object[] row = results.get();
        String uuid = (String) row[0];
        row[1] = ((String) row[1]).toLowerCase();
        date.setTime((Date) row[2]);

        // Prime the calendars here...
        Calendar cdate = Calendar.getInstance();
        cdate.setTime(startDate != null ? startDate : date.getTime());
        cdate.set(Calendar.HOUR_OF_DAY, 23);
        cdate.set(Calendar.MINUTE, 59);
        cdate.set(Calendar.SECOND, 59);
        cdate.set(Calendar.MILLISECOND, 999);

        Calendar end = Calendar.getInstance();
        end.setTimeInMillis(endDate != null ? endDate.getTime() : Long.MAX_VALUE);

        for (; this.compareCalendarsByDate(cdate, end) <= 0; cdate.add(Calendar.DATE, 1)) {
            while (this.compareCalendarsByDate(date, cdate) <= 0) {
                // Date is before our current date. Store the uuid's status so we can add it to
                // our counts later.
                cstatusmap.put(uuid, row);

                if (!results.next()) {
                    if (endDate == null) {
                        end.setTimeInMillis(cdate.getTimeInMillis());
                    }

                    break;
                }

                row = (Object[]) results.get();
                uuid = (String) row[0];
                row[1] = ((String) row[1]).toLowerCase();
                date.setTime((Date) row[2]);
            }

            Date hashdate = cdate.getTime();
            Map<String, Integer> statusmap = new HashMap<String, Integer>();

            // Go through and add up all our counts for the day.
            for (Object[] cstatus : cstatusmap.values()) {
                if (cstatus[3] == null || this.compareDatesByDate(hashdate, (Date) cstatus[3]) < 0) {
                    Integer count = statusmap.get((String) cstatus[1]);
                    statusmap.put((String) cstatus[1], (count != null ? count + 1 : 1));
                }
            }

            resultmap.put(hashdate, statusmap);
        }
    }

    results.close();

    // Pagination
    // This is horribly inefficient, but the only way to do it with the current implementation.
    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(resultmap.size());

        int offset = (pageRequest.getPage() - 1) * pageRequest.getPerPage();
        int nextpage = offset + pageRequest.getPerPage();

        // Trim results. :(
        Iterator<Date> iterator = resultmap.keySet().iterator();
        for (int pos = 0; iterator.hasNext(); ++pos) {
            iterator.next();

            if (pos < offset || pos >= nextpage) {
                iterator.remove();
            }
        }
    }

    page.setPageData(resultmap);
    return page;
}

From source file:org.candlepin.model.ColumnarResultIteratorTest.java

License:Open Source License

@Test
public void testHasNextWithElements() {
    this.ownerCurator.create(TestUtil.createOwner());
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0, false);

    try {/*from w w  w  .  ja  v  a 2  s .  c o m*/
        assertTrue(iterator.hasNext());
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.ColumnarResultIteratorTest.java

License:Open Source License

@Test
public void testHasNextWithoutElements() {
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0, false);

    try {// w w w .  jav  a2s. c  o m
        assertFalse(iterator.hasNext());
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.ColumnarResultIteratorTest.java

License:Open Source License

@Test
public void testNextWithElements() {
    Owner owner1 = TestUtil.createOwner();
    Owner owner2 = TestUtil.createOwner();
    Owner owner3 = TestUtil.createOwner();
    this.ownerCurator.create(owner1);
    this.ownerCurator.create(owner2);
    this.ownerCurator.create(owner3);

    Query query = this.session.createQuery("SELECT o FROM Owner o");

    ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0, false);

    try {/*from ww  w.j av a2s.  c om*/
        List<Owner> owners = new LinkedList<>();

        // Note: Since we're testing everything in isolation here, we can't
        // be expecting .hasNext to be functional here. :)
        owners.add(iterator.next());
        owners.add(iterator.next());
        owners.add(iterator.next());

        assertTrue(owners.contains(owner1));
        assertTrue(owners.contains(owner2));
        assertTrue(owners.contains(owner3));
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.ColumnarResultIteratorTest.java

License:Open Source License

@Test(expected = NoSuchElementException.class)
public void testNextWithoutElements() {
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0, false);

    try {//from  w w w  .j  a  va2  s  .  c o m
        iterator.next(); // Kaboom
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.ColumnarResultIteratorTest.java

License:Open Source License

@Test(expected = UnsupportedOperationException.class)
public void testRemoveAlwaysFails() {
    this.ownerCurator.create(TestUtil.createOwner());
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0, false);

    try {//from  w w  w .  j a  v a2s .c  o m
        iterator.next();
        iterator.remove();
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.DetachedCandlepinQuery.java

License:Open Source License

/**
 * {@inheritDoc}// www.  j av  a  2 s. c o m
 */
@Override
@Transactional
@SuppressWarnings("unchecked")
public int forEach(int column, boolean evict, ResultProcessor<T> processor) {
    if (processor == null) {
        throw new IllegalArgumentException("processor is null");
    }

    Criteria executable = this.getExecutableCriteria();

    // We always override the cache mode here to ensure we don't evict things that may be in
    // cache from another request.
    if (evict) {
        executable.setCacheMode(CacheMode.GET);
    }

    ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;

    try {
        boolean cont = true;

        if (evict) {
            while (cont && cursor.next()) {
                T result = (T) cursor.get(column);

                cont = processor.process(result);
                this.session.evict(result);

                ++count;
            }
        } else {
            while (cont && cursor.next()) {
                cont = processor.process((T) cursor.get(column));
                ++count;
            }
        }
    } finally {
        cursor.close();
    }

    return count;
}

From source file:org.candlepin.model.DetachedCandlepinQuery.java

License:Open Source License

/**
 * {@inheritDoc}//from   www.  j  ava2s  . c  om
 */
@Override
@Transactional
public int forEachRow(ResultProcessor<Object[]> processor) {
    if (processor == null) {
        throw new IllegalArgumentException("processor is null");
    }

    Criteria executable = this.getExecutableCriteria();
    ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;

    try {
        boolean cont = true;

        while (cont && cursor.next()) {
            cont = processor.process(cursor.get());
            ++count;
        }
    } finally {
        cursor.close();
    }

    return count;
}