Example usage for org.hibernate Criteria setReadOnly

List of usage examples for org.hibernate Criteria setReadOnly

Introduction

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

Prototype

public Criteria setReadOnly(boolean readOnly);

Source Link

Document

Set the read-only/modifiable mode for entities and proxies loaded by this Criteria.

Usage

From source file:com.bloatit.data.queries.DaoUserContentQuery.java

License:Open Source License

/**
 * Instantiates a new dao user content query.
 * /*from  ww w.j a  v  a2  s .  c om*/
 * @param criteria the criteria to use for this query
 */
protected DaoUserContentQuery(final Criteria criteria) {
    super(criteria);
    criteria.createAlias("member", "m");
    criteria.setReadOnly(true);
}

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);
        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();//w ww .  j  a  v  a2s  . c om
                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.blockstorage.async.SnapshotDeleter.java

License:Open Source License

private void deleteFromOSG() {
    try {/*from   ww w  .  jav a 2s  . c o m*/
        // Get the snapshots that are deleted from EBS but not yet deleted from OSG, 
        // in reverse time order so we never try to delete a parent before a child
        List<SnapshotInfo> snapshotsToBeDeleted = null;
        try (TransactionResource tr = Entities.transactionFor(SnapshotInfo.class)) {
            snapshotsToBeDeleted = Entities.criteriaQuery(Entities.restriction(SnapshotInfo.class)
                    .equal(SnapshotInfo_.status, StorageProperties.Status.deletedfromebs.toString()).build())
                    .orderByDesc(SnapshotInfo_.startTime).list();
            tr.commit();
        } catch (Exception e) {
            LOG.warn("Failed database lookup of snapshots marked for deletion from OSG", e);
            return;
        }

        if (snapshotsToBeDeleted != null && !snapshotsToBeDeleted.isEmpty()) {
            LOG.trace("Deleting snapshots from OSG");
            for (SnapshotInfo snap : snapshotsToBeDeleted) {
                try {
                    String snapshotId = snap.getSnapshotId();

                    LOG.debug("Snapshot " + snapshotId
                            + " was marked for deletion from OSG. Evaluating prerequisites for cleanup...");
                    if (snap.getIsOrigin() == null) { // old snapshot prior to 4.4
                        LOG.debug("Snapshot " + snapshotId
                                + " may have been created prior to incremental snapshot support");
                        deleteSnapFromOSG(snap); // delete snapshot
                    } else if (snap.getIsOrigin()) { // snapshot originated in the same az
                        LOG.debug("Snapshot " + snapshotId
                                + " originates from this az, verifying if it's needed to restore other snapshots");
                        List<SnapshotInfo> nextSnaps = null;
                        try (TransactionResource tr = Entities.transactionFor(SnapshotInfo.class)) {

                            SnapshotInfo nextSnapSearch = new SnapshotInfo();
                            nextSnapSearch.setScName(snap.getScName());
                            nextSnapSearch.setVolumeId(snap.getVolumeId());
                            nextSnapSearch.setIsOrigin(Boolean.TRUE);
                            nextSnapSearch.setPreviousSnapshotId(snap.getSnapshotId());
                            Criteria search = Entities.createCriteria(SnapshotInfo.class);
                            search.add(Example.create(nextSnapSearch).enableLike(MatchMode.EXACT));
                            search.add(StorageProperties.SNAPSHOT_DELTA_RESTORATION_CRITERION);
                            search.setReadOnly(true);

                            nextSnaps = (List<SnapshotInfo>) search.list();
                            tr.commit();
                        } catch (Exception e) {
                            LOG.warn("Failed to lookup snapshots that may depend on " + snapshotId
                                    + " for reconstruction", e);
                            return;
                        }

                        if (nextSnaps != null && !nextSnaps.isEmpty()) {
                            // Found deltas that might depend on this snapshot for reconstruction, don't delete.
                            // Normally there will be only 1 next snap, optimize for that case.
                            String nextSnapIds = nextSnaps.get(0).getSnapshotId();
                            if (nextSnaps.size() > 1) {
                                for (int nextSnapIdNum = 1; nextSnapIdNum < nextSnaps.size(); nextSnapIdNum++) {
                                    nextSnapIds = nextSnapIds + ", "
                                            + nextSnaps.get(nextSnapIdNum).getSnapshotId();
                                }
                            }
                            LOG.debug("Snapshot " + snapshotId
                                    + " is required for restoring other snapshots in the system."
                                    + " Cannot delete from OSG. Direct children of this snapshot: "
                                    + nextSnapIds);
                        } else {
                            LOG.debug("Snapshot " + snapshotId
                                    + " is not required for restoring other snapshots in the system");
                            deleteSnapFromOSG(snap); // delete snapshot
                        }
                    } else { // snapshot originated in a different az
                        // skip evaluation and just mark the snapshot deleted, let the source az deal with the osg remnants TODO fix this later
                        LOG.debug("Snapshot " + snapshotId
                                + " orignated from a different az, let the source az deal with deletion from OSG");
                        markSnapDeleted(snapshotId);
                    }
                } catch (Exception e) {
                    LOG.warn("Failed to process deletion for " + snap.getSnapshotId()
                            + " on ObjectStorageGateway", e);
                    continue;
                }
            }
        } else {
            LOG.trace("No snapshots marked for deletion from OSG");
        }
    } catch (Exception e) { // could catch InterruptedException
        LOG.warn("Unable to remove snapshots marked for deletion from OSG", e);
        return;
    }
}

From source file:com.eucalyptus.blockstorage.BlockStorageController.java

License:Open Source License

/**
 * Checks to see if a new snapshot of size volSize will exceed the quota
 * @param volSize/*w  ww.  j a v a  2  s  .  com*/
 * @return
 */
private boolean totalSnapshotSizeLimitExceeded(String snapshotId, int volSize) throws EucalyptusCloudException {

    int totalSnapshotSize = 0;
    EntityTransaction dbTrans = Entities.get(SnapshotInfo.class);
    try {
        Criteria query = Entities.createCriteria(SnapshotInfo.class);
        query.setReadOnly(true);

        //Only look for snaps that are not failed and not error      
        ImmutableSet<String> excludedStates = ImmutableSet.of(StorageProperties.Status.failed.toString(),
                StorageProperties.Status.error.toString(), StorageProperties.Status.deleted.toString());

        query.add(Restrictions.not(Restrictions.in("status", excludedStates)));

        //The listing may include duplicates (for snapshots cached on multiple clusters), this set ensures each unique snap id is counted only once.
        HashSet<String> idSet = new HashSet<String>();
        List<SnapshotInfo> snapshots = (List<SnapshotInfo>) query.list();
        for (SnapshotInfo snap : snapshots) {
            totalSnapshotSize += (snap.getSizeGb() != null && idSet.add(snap.getSnapshotId()) ? snap.getSizeGb()
                    : 0);
        }
        int sizeLimitGB = WalrusInfo.getWalrusInfo().getStorageMaxTotalSnapshotSizeInGb();
        LOG.debug("Snapshot " + snapshotId + " checking snapshot total size of  " + totalSnapshotSize
                + " against limit of " + sizeLimitGB);
        return (totalSnapshotSize + volSize) > sizeLimitGB;
    } catch (final Throwable e) {
        LOG.error("Error finding total snapshot used size " + e.getMessage());
        throw new EucalyptusCloudException("Failed to check snapshot total size limit", e);
    } finally {
        if (dbTrans.isActive()) {
            dbTrans.rollback();
        }
    }
}

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);
    }//w  w w.  j a  va  2 s . c om
    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 w  w w. ja  v a  2s.c  o m*/
        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.DbBucketMetadataManagerImpl.java

License:Open Source License

@Override
public List<Bucket> lookupBucketsByOwner(String ownerCanonicalId) throws MetadataOperationFailureException {
    Bucket searchBucket = new Bucket().withState(BucketState.extant);
    searchBucket.setOwnerCanonicalId(ownerCanonicalId);
    List<Bucket> buckets = null;
    try (TransactionResource trans = Entities.transactionFor(Bucket.class)) {
        Criteria searchCriteria = Entities.createCriteria(Bucket.class);
        Example example = Example.create(searchBucket);
        searchCriteria.add(example);/*from   w  ww  . ja  v  a  2s. c  om*/
        searchCriteria.addOrder(Order.asc("bucketName"));
        searchCriteria.setReadOnly(true);
        buckets = searchCriteria.list();
        trans.commit();
        return buckets;
    } catch (Exception e) {
        LOG.error("Error listing buckets for user " + ownerCanonicalId + " due to DB transaction error", e);
        throw new MetadataOperationFailureException(e);
    }
}

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

License:Open Source License

@Override
public List<Bucket> lookupBucketsByState(BucketState state) throws TransactionException {
    Bucket searchBucket = new Bucket().withState(state);
    List<Bucket> buckets = null;
    try (TransactionResource trans = Entities.transactionFor(Bucket.class)) {
        Criteria searchCriteria = Entities.createCriteria(Bucket.class);
        Example example = Example.create(searchBucket);
        searchCriteria.add(example);/* w ww.  j  av  a  2  s.c o  m*/
        searchCriteria.addOrder(Order.asc("bucketName"));
        searchCriteria.setReadOnly(true);
        buckets = searchCriteria.list();
        trans.commit();
        return buckets;
    } catch (Exception e) {
        LOG.error("Error listing buckets in the state: " + state + " due to DB transaction error", e);
        throw e;
    }
}

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

License:Open Source License

@Override
public long getTotalSize(Bucket bucket) throws Exception {
    try (TransactionResource trans = Entities.transactionFor(PartEntity.class)) {
        Criteria queryCriteria = Entities.createCriteria(PartEntity.class)
                .add(Restrictions.or(Restrictions.eq("state", ObjectState.creating),
                        Restrictions.eq("state", ObjectState.extant)))
                .setProjection(Projections.sum("size"));
        if (bucket != null) {
            queryCriteria = getSearchByBucket(queryCriteria, bucket);
        }/* w w w. j a v  a 2s .c  om*/
        queryCriteria.setReadOnly(true);
        final Number count = (Number) queryCriteria.uniqueResult();
        return count == null ? 0 : count.longValue();
    } catch (Throwable e) {
        LOG.error("Error getting part total size for bucket " + bucket.getBucketName(), e);
        throw new Exception(e);
    }
}

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.c  o  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();
    }
}