List of usage examples for org.hibernate Criteria scroll
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException;
From source file:mitm.common.security.certstore.dao.X509CertStoreDAOHibernate.java
License:Open Source License
private ScrollableResults findByCriterionScrollable(Collection<DatabaseCriterion> criterions, Integer firstResult, Integer maxResults) { Criteria criteria = createCriteria(criterions); if (firstResult != null) { criteria.setFirstResult(firstResult); }//from w w w . j a va2 s .c om if (maxResults != null) { criteria.setMaxResults(maxResults); } /* * Sort on creation date */ criteria.addOrder(Order.asc(getColumnName(Field.CREATION_DATE))); return criteria.scroll(ScrollMode.FORWARD_ONLY); }
From source file:mitm.common.security.crlstore.dao.X509CRLStoreDAOHibernate.java
License:Open Source License
private ScrollableResults getEntriesScrollable(CRLSelector crlSelector, Integer firstResult, Integer maxResults) {//from w w w . j a v a 2 s.co m Criteria criteria = createCriteria(entityName); criteria.add(Restrictions.eq("storeName", storeName)); if (crlSelector instanceof X509CRLSelector) { /* we can do some optimizations by using SQL */ X509CRLSelector x509CRLSelector = (X509CRLSelector) crlSelector; addSelectorCriterias(x509CRLSelector, criteria); } /* sort on thisUpdate date */ criteria.addOrder(Order.desc("crl.thisUpdate")); if (firstResult != null) { criteria.setFirstResult(firstResult); } if (maxResults != null) { criteria.setMaxResults(maxResults); } return criteria.scroll(ScrollMode.FORWARD_ONLY); }
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 www . j av a2 s. c o 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// ww w. ja v a 2 s . c o 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.model.DetachedCandlepinQuery.java
License:Open Source License
/** * {@inheritDoc}/*w w w .j av a 2s . 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}/* w w w. java 2s. co m*/ */ @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; }
From source file:org.candlepin.model.DetachedCandlepinQuery.java
License:Open Source License
/** * {@inheritDoc}//from w w w . j a va 2s .com */ @Override public ResultIterator<T> iterate(int column, boolean evict) { 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); return new ColumnarResultIterator<>(this.session, cursor, column, evict); }
From source file:org.candlepin.model.DetachedCandlepinQuery.java
License:Open Source License
/** * {@inheritDoc}/* w w w . j a v a2 s .c o m*/ */ @Override public ResultIterator<Object[]> iterateByRow() { Criteria executable = this.getExecutableCriteria(); ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY); return new RowResultIterator(cursor); }
From source file:org.compass.gps.device.hibernate.indexer.ScrollableHibernateIndexEntitiesIndexer.java
License:Apache License
public void performIndex(CompassSession session, IndexEntity[] entities) { for (IndexEntity entity : entities) { EntityInformation entityInformation = (EntityInformation) entity; if (device.isFilteredForIndex(entityInformation.getName())) { continue; }/*from w ww .j a va 2 s .c o m*/ if (!device.isRunning()) { return; } ScrollableResults cursor = null; Session hibernateSession = device.getSessionFactory().openSession(); hibernateSession.setCacheMode(CacheMode.IGNORE); Transaction hibernateTransaction = null; try { hibernateTransaction = hibernateSession.beginTransaction(); if (log.isDebugEnabled()) { log.debug(device.buildMessage("Indexing entities [" + entityInformation.getName() + "] using query [" + entityInformation.getQueryProvider() + "]")); } Criteria criteria = entityInformation.getQueryProvider().createCriteria(hibernateSession, entityInformation); if (criteria != null) { if (performOrderById) { Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName()); if (performOrder == null || performOrder) { ClassMetadata metadata = hibernateSession.getSessionFactory() .getClassMetadata(entityInformation.getName()); String idPropName = metadata.getIdentifierPropertyName(); if (idPropName != null) { criteria.addOrder(Order.asc(idPropName)); } } } criteria.setFetchSize(device.getFetchCount()); cursor = criteria.scroll(ScrollMode.FORWARD_ONLY); } else { Query query = entityInformation.getQueryProvider().createQuery(hibernateSession, entityInformation); cursor = query.scroll(ScrollMode.FORWARD_ONLY); } // store things in row buffer to allow using batch fetching in Hibernate RowBuffer buffer = new RowBuffer(session, hibernateSession, device.getFetchCount()); Object prev = null; while (true) { try { if (!cursor.next()) { break; } } catch (ObjectNotFoundException e) { continue; } Object item = cursor.get(0); if (prev != null && item != prev) { buffer.put(prev); } prev = item; if (buffer.shouldFlush()) { // put also the item/prev since we are clearing the session // in the flush process buffer.put(prev); buffer.flush(); prev = null; } } if (prev != null) { buffer.put(prev); } buffer.close(); cursor.close(); hibernateTransaction.commit(); } catch (Exception e) { log.error(device.buildMessage("Failed to index the database"), e); if (cursor != null) { try { cursor.close(); } catch (Exception e1) { log.warn(device.buildMessage("Failed to close cursor on error, ignoring"), e1); } } if (hibernateTransaction != null) { try { hibernateTransaction.rollback(); } catch (Exception e1) { log.warn("Failed to rollback Hibernate", e1); } } if (!(e instanceof HibernateGpsDeviceException)) { throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e); } throw (HibernateGpsDeviceException) e; } finally { hibernateSession.close(); session.close(); } } }
From source file:org.compass.gps.device.jpa.indexer.HibernateJpaIndexEntitiesIndexer.java
License:Apache License
public void performIndex(CompassSession session, IndexEntity[] entities) { for (IndexEntity indexEntity : entities) { EntityInformation entityInformation = (EntityInformation) indexEntity; if (jpaGpsDevice.isFilteredForIndex(entityInformation.getName())) { continue; }// ww w. ja va2 s.c om int fetchCount = jpaGpsDevice.getFetchCount(); if (!jpaGpsDevice.isRunning()) { return; } EntityManagerWrapper wrapper = jpaGpsDevice.getEntityManagerWrapper().newInstance(); ScrollableResults cursor = null; try { wrapper.open(); HibernateEntityManager entityManager = (HibernateEntityManager) wrapper.getEntityManager(); entityManager.getSession().setCacheMode(CacheMode.IGNORE); if (log.isDebugEnabled()) { log.debug(jpaGpsDevice.buildMessage("Indexing entities [" + entityInformation.getName() + "] using query [" + entityInformation.getQueryProvider() + "]")); } if (entityInformation.getQueryProvider() instanceof HibernateJpaQueryProvider) { Criteria criteria = ((HibernateJpaQueryProvider) entityInformation.getQueryProvider()) .createCriteria(entityManager, entityInformation); if (criteria != null) { if (performOrderById) { Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName()); if (performOrder == null || performOrder) { ClassMetadata metadata = entityManager.getSession().getSessionFactory() .getClassMetadata(entityInformation.getName()); String idPropName = metadata.getIdentifierPropertyName(); if (idPropName != null) { criteria.addOrder(Order.asc(idPropName)); } } } criteria.setFetchSize(fetchCount); cursor = criteria.scroll(ScrollMode.FORWARD_ONLY); } } if (cursor == null) { HibernateQuery query = (HibernateQuery) entityInformation.getQueryProvider() .createQuery(entityManager, entityInformation); cursor = query.getHibernateQuery().scroll(ScrollMode.FORWARD_ONLY); } // store things in row buffer to allow using batch fetching in Hibernate RowBuffer buffer = new RowBuffer(session, entityManager.getSession(), fetchCount); Object prev = null; while (true) { try { if (!cursor.next()) { break; } } catch (ObjectNotFoundException e) { continue; } Object item = cursor.get(0); if (item != prev && prev != null) { buffer.put(prev); } prev = item; if (buffer.shouldFlush()) { // put also the item/prev since we are clearing the session // in the flush process buffer.put(prev); buffer.flush(); prev = null; } } if (prev != null) { buffer.put(prev); } buffer.close(); cursor.close(); entityManager.clear(); wrapper.close(); } catch (Exception e) { log.error(jpaGpsDevice.buildMessage("Failed to index the database"), e); if (cursor != null) { try { cursor.close(); } catch (Exception e1) { log.warn(jpaGpsDevice.buildMessage("Failed to close cursor on error, ignoring"), e1); } } wrapper.closeOnError(); if (!(e instanceof JpaGpsDeviceException)) { throw new JpaGpsDeviceException(jpaGpsDevice.buildMessage("Failed to index the database"), e); } throw (JpaGpsDeviceException) e; } } }