Example usage for org.hibernate Criteria setMaxResults

List of usage examples for org.hibernate Criteria setMaxResults

Introduction

In this page you can find the example usage for org.hibernate Criteria setMaxResults.

Prototype

public Criteria setMaxResults(int maxResults);

Source Link

Document

Set a limit upon the number of objects to be retrieved.

Usage

From source file:com.emergya.persistenceGeo.dao.impl.MultiSirDatabaseGenericHibernateDAOImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// ww w  . j  a v a 2  s  .  c om
public List<T> findAllFromTo(Integer first, Integer last) {
    Criteria criteria = getSession().createCriteria(persistentClass);
    criteria.setFirstResult(first);
    criteria.setMaxResults(last - first);
    return criteria.list();
}

From source file:com.emergya.persistenceGeo.dao.impl.MultiSirDatabaseGenericHibernateDAOImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  w  w w.  j  av  a  2s . c  o m
public List<T> findOrdered(Integer first, Integer last, String orderField, boolean ascending) {
    Criteria criteria = getSession().createCriteria(persistentClass);
    criteria.setFirstResult(first);
    criteria.setMaxResults(last - first);

    if (ascending) {
        criteria.addOrder(Order.asc(orderField));
    } else {
        criteria.addOrder(Order.desc(orderField));
    }
    return criteria.list();
}

From source file:com.eryansky.common.orm.core.hibernate.support.HibernateSupportDao.java

License:Apache License

/**
 * ?Criteria,.//from  ww w  .j a  v a2  s. c o m
 *
 * @param c Hibernate Criteria
 * @param pageRequest ?
 *
 * @return {@link org.hibernate.Criteria}
 */
protected Criteria setPageRequestToCriteria(Criteria c, PageRequest pageRequest) {
    Assert.isTrue(pageRequest.getPageSize() > 0, "?0");

    c.setFirstResult(pageRequest.getOffset());
    c.setMaxResults(pageRequest.getPageSize());

    if (pageRequest.isOrderBySetted()) {
        for (PageRequest.Sort sort : pageRequest.getSort()) {
            Order order = null;
            if (sort.getDir().equals(PageRequest.Sort.ASC)) {
                order = Order.asc(sort.getProperty());
            } else {
                order = Order.desc(sort.getProperty());
            }
            c.addOrder(order);
        }
    }

    return c;
}

From source file:com.eucalyptus.blockstorage.async.SnapshotCreator.java

License:Open Source License

private SnapshotInfo fetchPreviousSnapshot(int maxDeltas) throws Exception {

    SnapshotInfo prevSnapToAssign = null;
    SnapshotInfo currSnap = Transactions.find(new SnapshotInfo(snapshotId));

    try (TransactionResource tr = Entities.transactionFor(SnapshotInfo.class)) {

        // Find the most recent snapshot that is not in one of the states that
        // is ineligible to use for creating a snap delta.  
        SnapshotInfo prevEligibleSnapSearch = new SnapshotInfo();
        prevEligibleSnapSearch.setVolumeId(currSnap.getVolumeId());
        Criteria search = Entities.createCriteria(SnapshotInfo.class);
        search.add(Example.create(prevEligibleSnapSearch).enableLike(MatchMode.EXACT));
        search.add(Restrictions.and(StorageProperties.SNAPSHOT_DELTA_GENERATION_CRITERION,
                Restrictions.lt("startTime", currSnap.getStartTime())));
        search.addOrder(Order.desc("startTime"));
        search.setReadOnly(true);//from www  . j av  a  2s  .  com
        search.setMaxResults(1); // only return the latest one

        List<SnapshotInfo> prevEligibleSnapList = (List<SnapshotInfo>) search.list();

        boolean committed = false;

        if (prevEligibleSnapList != null && prevEligibleSnapList.size() > 0
                && (prevSnapToAssign = prevEligibleSnapList.get(0)) != null) {
            // Found an eligible previous snapshot to use as a parent for this 
            // snapshot, if we make it a delta.
            if (prevSnapToAssign.getSnapshotLocation() != null && prevSnapToAssign.getIsOrigin() != null) {
                LOG.info(this.volumeId
                        + " has been snapshotted and uploaded before. Most recent such snapshot is "
                        + prevSnapToAssign.getSnapshotId());

                // Get all the restorable snapshots for this volume, earlier than the current snapshot
                SnapshotInfo prevRestorableSnapsSearch = new SnapshotInfo();
                prevRestorableSnapsSearch.setVolumeId(currSnap.getVolumeId());
                search = Entities.createCriteria(SnapshotInfo.class);
                search.add(Example.create(prevRestorableSnapsSearch).enableLike(MatchMode.EXACT));
                search.add(Restrictions.and(StorageProperties.SNAPSHOT_DELTA_RESTORATION_CRITERION,
                        Restrictions.lt("startTime", currSnap.getStartTime())));
                search.addOrder(Order.desc("startTime"));
                search.setReadOnly(true);
                List<SnapshotInfo> prevRestorableSnapsList = (List<SnapshotInfo>) search.list();
                tr.commit();
                committed = true;

                // Get the snap chain ending with the previous snapshot (not the current)
                List<SnapshotInfo> snapChain = blockStorageUtilSvc.getSnapshotChain(prevRestorableSnapsList,
                        prevSnapToAssign.getSnapshotId());
                int numDeltas = 0;
                if (snapChain == null || snapChain.size() == 0) {
                    // This should never happen. The chain should always include the 
                    // parent (previous) snapshot we already found. But create it as a 
                    // full snapshot instead of failing, to account for the unknown case
                    // that might not prevent an OK full snapshot.
                    LOG.error("Did not find the current snapshot's previous snapshot "
                            + prevSnapToAssign.getSnapshotId() + " in the restorable snapshots list. "
                            + "The current snapshot " + currSnap.getSnapshotId()
                            + " will be created as a full snapshot.");
                } else if (snapChain.get(0).getPreviousSnapshotId() != null) {
                    // This should never happen. The first snapshot in the chain
                    // should always be a full snapshot. But create it as a 
                    // full snapshot instead of failing, to account for the unknown case
                    // that might not prevent an OK full snapshot.
                    LOG.error("First snapshot " + snapChain.get(0).getSnapshotId() + " in the chain of "
                            + snapChain.size() + " snapshots is not a full snapshot. The current snapshot "
                            + currSnap.getSnapshotId() + " will be created as a full snapshot.");
                } else {
                    numDeltas = snapChain.size() - 1;
                    LOG.info(this.volumeId + " has " + numDeltas
                            + " delta(s) since the last full checkpoint. Max limit is " + maxDeltas);
                    if (numDeltas < maxDeltas) {
                        return prevSnapToAssign;
                    }
                }
            } else {
                LOG.info(this.volumeId
                        + " has not been snapshotted and/or uploaded after the support for incremental snapshots was added");
            }
        } else {
            LOG.info(this.volumeId + " has no prior active snapshots in the system");
        }
        if (!committed) {
            tr.commit();
        }
    } catch (Exception e) {
        LOG.warn("Failed to look up previous snapshots for " + this.volumeId, e); // return null on exception, forces entire snapshot to get uploaded
    }
    return null;
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.NextTokenUtils.java

License:Open Source License

public static Criteria addNextTokenConstraints(Integer maxRecords, String nextToken, Date nextTokenCreated,
        Criteria criteria) {
    if (nextTokenCreated != null) {
        // add (WHERE creationTimestamp > nextTokenCreated OR 
        // (creationTimestamp = nextTokenCreated AND naturalId > nextToken
        Junction or = Restrictions.disjunction();
        or.add(Restrictions.gt("creationTimestamp", nextTokenCreated));
        Junction and = Restrictions.conjunction();
        and.add(Restrictions.eq("creationTimestamp", nextTokenCreated));
        and.add(Restrictions.gt("naturalId", nextToken));
        or.add(and);/*from ww  w.  j a  v  a 2  s  .c  o m*/
        criteria.add(or);
    }
    criteria.addOrder(Order.asc("creationTimestamp"));
    criteria.addOrder(Order.asc("naturalId"));
    if (maxRecords != null) {
        criteria.setMaxResults(maxRecords);
    }
    return criteria;
}

From source file:com.eucalyptus.entities.Entities.java

License:Open Source License

private static Criteria setOptions(final Criteria criteria, final QueryOptions options) {
    final Integer maxResults = options.getMaxResults();
    if (maxResults != null) {
        criteria.setMaxResults(maxResults);
    }/*ww w .  java2 s .  c  o  m*/
    final Integer fetchSize = options.getFetchSize();
    if (fetchSize != null) {
        criteria.setFetchSize(fetchSize);
    }
    final Boolean cacheable = options.getCacheable();
    if (cacheable != null) {
        criteria.setCacheable(cacheable);
    }
    final Boolean readonly = options.getReadonly();
    if (readonly != null) {
        criteria.setReadOnly(readonly);
    }
    final Criterion criterion = options.getCriterion();
    if (criterion != null) {
        criteria.add(criterion);
    }
    return criteria;
}

From source file:com.eucalyptus.objectstorage.DbObjectManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<ObjectEntity> listVersionsPaginated(final Bucket bucket, int maxEntries, String prefix,
        String delimiter, String fromKeyMarker, String fromVersionId, boolean latestOnly) throws Exception {

    EntityTransaction db = Entities.get(ObjectEntity.class);
    try {//from www. j  a v  a 2s  . com
        PaginatedResult<ObjectEntity> result = new PaginatedResult<ObjectEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxEntries >= 0) {
            final int queryStrideSize = maxEntries + 1;
            ObjectEntity searchObj = new ObjectEntity();
            searchObj.setBucketName(bucket.getBucketName());

            // Return latest version, so exclude delete markers as well.
            // This makes listVersion act like listObjects
            if (latestOnly) {
                searchObj.setDeleted(false);
                searchObj.setIsLatest(true);
            }

            Criteria objCriteria = Entities.createCriteria(ObjectEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchObj));
            objCriteria.add(ObjectEntity.QueryHelpers.getNotPendingRestriction());
            objCriteria.add(ObjectEntity.QueryHelpers.getNotDeletingRestriction());
            objCriteria.addOrder(Order.asc("objectKey"));
            objCriteria.addOrder(Order.desc("objectModifiedTimestamp"));
            objCriteria.setMaxResults(queryStrideSize);

            if (!Strings.isNullOrEmpty(fromKeyMarker)) {
                objCriteria.add(Restrictions.gt("objectKey", fromKeyMarker));
            } else {
                fromKeyMarker = "";
            }

            if (!Strings.isNullOrEmpty(fromVersionId)) {
                objCriteria.add(Restrictions.gt("versionId", fromVersionId));
            } else {
                fromVersionId = "";
            }

            if (!Strings.isNullOrEmpty(prefix)) {
                objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
            } else {
                prefix = "";
            }

            // Ensure not null.
            if (Strings.isNullOrEmpty(delimiter)) {
                delimiter = "";
            }

            List<ObjectEntity> objectInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            String prefixString = null;
            boolean useDelimiter = !Strings.isNullOrEmpty(delimiter);
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;
                prefixString = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                objectInfos = (List<ObjectEntity>) objCriteria.list();
                if (objectInfos == null) {
                    // nothing to do.
                    break;
                }

                for (ObjectEntity objectRecord : objectInfos) {
                    if (useDelimiter) {
                        // Check if it will get aggregated as a commonprefix
                        parts = objectRecord.getObjectKey().substring(prefix.length()).split(delimiter);
                        if (parts.length > 1) {
                            prefixString = prefix + parts[0] + delimiter;
                            if (!commonPrefixes.contains(prefixString)) {
                                if (resultKeyCount == maxEntries) {
                                    // This is a new record, so we know
                                    // we're truncating if this is true
                                    result.setIsTruncated(true);
                                    resultKeyCount++;
                                    break;
                                } else {
                                    // Add it to the common prefix set
                                    commonPrefixes.add(prefixString);
                                    result.lastEntry = prefixString;
                                    // count the unique commonprefix as a
                                    // single return entry
                                    resultKeyCount++;
                                }
                            } else {
                                // Already have this prefix, so skip
                            }
                            continue;
                        }
                    }

                    if (resultKeyCount == maxEntries) {
                        // This is a new (non-commonprefix) record, so
                        // we know we're truncating
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.entityList.add(objectRecord);
                    result.lastEntry = objectRecord;
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxEntries && objectInfos.size() <= maxEntries) {
                    break;
                }
            } while (resultKeyCount <= maxEntries);

            // Sort the prefixes from the hashtable and add to the reply
            if (commonPrefixes != null) {
                result.getCommonPrefixes().addAll(commonPrefixes);
                Collections.sort(result.getCommonPrefixes());
            }
        } else {
            throw new IllegalArgumentException("MaxKeys must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated object list of bucket " + bucket.getBucketName(), e);
        throw e;
    } finally {
        db.rollback();
    }
}

From source file:com.eucalyptus.objectstorage.metadata.DbMpuPartMetadataManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<PartEntity> listPartsForUpload(final Bucket bucket, final String objectKey,
        final String uploadId, final Integer partNumberMarker, final Integer maxParts) throws Exception {

    EntityTransaction db = Entities.get(PartEntity.class);
    try {/*from   w  ww. java 2 s. co m*/
        PaginatedResult<PartEntity> result = new PaginatedResult<PartEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxParts >= 0) {
            final int queryStrideSize = maxParts + 1;
            PartEntity searchPart = new PartEntity(bucket, objectKey, uploadId).withState(ObjectState.extant);

            Criteria objCriteria = Entities.createCriteria(PartEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchPart));
            objCriteria.addOrder(Order.asc("partNumber"));
            objCriteria.addOrder(Order.desc("objectModifiedTimestamp"));
            objCriteria.setMaxResults(queryStrideSize);

            if (partNumberMarker != null) {
                objCriteria.add(Restrictions.gt("partNumber", partNumberMarker));
            }
            objCriteria = getSearchByBucket(objCriteria, bucket);

            List<PartEntity> partInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                partInfos = (List<PartEntity>) objCriteria.list();
                if (partInfos == null) {
                    // nothing to do.
                    break;
                }

                for (PartEntity partRecord : partInfos) {

                    if (resultKeyCount == maxParts) {
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.getEntityList().add(partRecord);
                    result.setLastEntry(partRecord);
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxParts && partInfos.size() <= maxParts) {
                    break;
                }
            } while (resultKeyCount <= maxParts);
        } else {
            throw new IllegalArgumentException("MaxKeys must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated parts list for upload ID " + uploadId, e);
        throw e;
    } finally {
        db.rollback();
    }
}

From source file:com.eucalyptus.objectstorage.metadata.DbObjectMetadataManagerImpl.java

License:Open Source License

@Override
public PaginatedResult<ObjectEntity> listUploads(Bucket bucket, int maxUploads, String prefix, String delimiter,
        String keyMarker, String uploadIdMarker) throws Exception {

    try (TransactionResource trans = Entities.transactionFor(ObjectEntity.class)) {
        PaginatedResult<ObjectEntity> result = new PaginatedResult<ObjectEntity>();
        HashSet<String> commonPrefixes = new HashSet<String>();

        // Include zero since 'istruncated' is still valid
        if (maxUploads >= 0) {
            final int queryStrideSize = maxUploads + 1;
            ObjectEntity searchObj = new ObjectEntity();
            searchObj.withBucket(bucket); //This doesn't actually filter, but do it anyway
            searchObj.withState(ObjectState.mpu_pending);

            Criteria objCriteria = Entities.createCriteria(ObjectEntity.class);
            objCriteria.setReadOnly(true);
            objCriteria.setFetchSize(queryStrideSize);
            objCriteria.add(Example.create(searchObj));
            objCriteria.addOrder(Order.asc("objectKey"));
            objCriteria.setMaxResults(queryStrideSize);

            if (!Strings.isNullOrEmpty(keyMarker)) {
                objCriteria.add(Restrictions.gt("objectKey", keyMarker));
            } else {
                keyMarker = "";
            }/*from   www .j  a  va  2s .c  om*/

            if (!Strings.isNullOrEmpty(uploadIdMarker)) {
                objCriteria.add(Restrictions.gt("uploadId", uploadIdMarker));
            } else {
                uploadIdMarker = "";
            }

            if (!Strings.isNullOrEmpty(prefix)) {
                objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
            } else {
                prefix = "";
            }

            //Be sure to add the bucket restriction last
            objCriteria = getSearchByBucket(objCriteria, bucket);

            // Ensure not null.
            if (Strings.isNullOrEmpty(delimiter)) {
                delimiter = "";
            }

            List<ObjectEntity> objectInfos = null;
            int resultKeyCount = 0;
            String[] parts = null;
            String prefixString = null;
            boolean useDelimiter = !Strings.isNullOrEmpty(delimiter);
            int pages = 0;

            // Iterate over result sets of size maxkeys + 1 since
            // commonPrefixes collapse the list, we may examine many more
            // records than maxkeys + 1
            do {
                parts = null;
                prefixString = null;

                // Skip ahead the next page of 'queryStrideSize' results.
                objCriteria.setFirstResult(pages++ * queryStrideSize);

                objectInfos = (List<ObjectEntity>) objCriteria.list();
                if (objectInfos == null) {
                    // nothing to do.
                    break;
                }

                for (ObjectEntity objectRecord : objectInfos) {
                    if (useDelimiter) {
                        // Check if it will get aggregated as a commonprefix
                        parts = objectRecord.getObjectKey().substring(prefix.length()).split(delimiter);
                        if (parts.length > 1) {
                            prefixString = prefix + parts[0] + delimiter;
                            if (!prefixString.equals(keyMarker) && !commonPrefixes.contains(prefixString)) {
                                if (resultKeyCount == maxUploads) {
                                    // This is a new record, so we know
                                    // we're truncating if this is true
                                    result.setIsTruncated(true);
                                    resultKeyCount++;
                                    break;
                                } else {
                                    // Add it to the common prefix set
                                    commonPrefixes.add(prefixString);
                                    result.setLastEntry(prefixString);
                                    // count the unique commonprefix as a
                                    // single return entry
                                    resultKeyCount++;
                                }
                            } else {
                                // Already have this prefix, so skip
                            }
                            continue;
                        }
                    }

                    if (resultKeyCount == maxUploads) {
                        // This is a new (non-commonprefix) record, so
                        // we know we're truncating
                        result.setIsTruncated(true);
                        resultKeyCount++;
                        break;
                    }

                    result.getEntityList().add(objectRecord);
                    result.setLastEntry(objectRecord);
                    resultKeyCount++;
                }

                if (resultKeyCount <= maxUploads && objectInfos.size() <= maxUploads) {
                    break;
                }
            } while (resultKeyCount <= maxUploads);

            // Sort the prefixes from the hashtable and add to the reply
            if (commonPrefixes != null) {
                result.getCommonPrefixes().addAll(commonPrefixes);
                Collections.sort(result.getCommonPrefixes());
            }
        } else {
            throw new IllegalArgumentException("max uploads must be positive integer");
        }

        return result;
    } catch (Exception e) {
        LOG.error("Error generating paginated multipart upload list for bucket " + bucket.getBucketName(), e);
        throw e;
    }
}

From source file:com.eucalyptus.objectstorage.metadata.DbObjectMetadataManagerImpl.java

License:Open Source License

@Override
public List<ObjectEntity> lookupObjectVersions(Bucket bucket, String objectKey, int numResults)
        throws Exception {
    ObjectEntity searchObj = new ObjectEntity().withBucket(bucket).withState(ObjectState.extant)
            .withKey(objectKey);/*  w  w w. j  a v  a2 s.  com*/

    List<ObjectEntity> objectInfos = null;
    try (TransactionResource tran = Entities.transactionFor(ObjectEntity.class)) {
        Criteria objCriteria = Entities.createCriteria(ObjectEntity.class);
        objCriteria.setMaxResults(numResults);
        objCriteria.setReadOnly(true);
        objCriteria.add(Example.create(searchObj));
        objCriteria.addOrder(Order.desc("objectModifiedTimestamp"));

        objCriteria = getSearchByBucket(objCriteria, bucket);
        objectInfos = objCriteria.list();
        tran.commit();
    } catch (Exception ex) {
        LOG.warn("exception caught while retrieving all versions of object " + objectKey + " in bucket "
                + bucket.getBucketName());
        throw ex;
    }
    return objectInfos;
}