Example usage for org.hibernate.criterion Restrictions not

List of usage examples for org.hibernate.criterion Restrictions not

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions not.

Prototype

public static Criterion not(Criterion expression) 

Source Link

Document

Return the negation of an expression

Usage

From source file:com.eucalyptus.autoscaling.common.internal.instances.PersistenceAutoScalingInstances.java

License:Open Source License

@Override
public void markMissingInstancesUnhealthy(final AutoScalingGroupMetadata group,
        final Collection<String> instanceIds) throws AutoScalingMetadataException {
    final AutoScalingInstance example = exampleForGroup(group);
    example.setHealthStatus(HealthStatus.Healthy);

    final List<AutoScalingInstance> instancesToMark = persistenceSupport.listByExample(example,
            LifecycleState.InService,// www  .  ja  v  a2 s  .  c om
            instanceIds.isEmpty() ? Restrictions.conjunction()
                    : Restrictions.not(Property.forName("displayName").in(instanceIds)),
            Collections.<String, String>emptyMap(), Functions.<AutoScalingInstance>identity());

    for (final AutoScalingInstance instance : instancesToMark) {
        try {
            persistenceSupport.updateByExample(AutoScalingInstance.withUuid(instance.getNaturalId()),
                    group.getOwner(), instance.getInstanceId(), new Callback<AutoScalingInstance>() {
                        @Override
                        public void fire(final AutoScalingInstance instance) {
                            if (instance.healthStatusGracePeriodExpired()) {
                                logger.info("Marking instance unhealthy: " + instance.getInstanceId());
                                instance.setHealthStatus(HealthStatus.Unhealthy);
                            } else {
                                logger.debug("Instance not healthy but within grace period: "
                                        + instance.getInstanceId());
                            }
                        }
                    });
        } catch (final AutoScalingMetadataNotFoundException e) {
            // removed, no need to mark unhealthy
        }
    }
}

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//from  www.j  a v  a  2  s. co m
 * @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.compute.common.internal.tags.FilterSupport.java

License:Open Source License

/**
 * Construct a criterion from a filter pattern.
 *
 * A Pattern is constructed from the given filter, as per AWS:
 *
 *  Filters support the following wildcards:
 *
 *    *: Matches zero or more characters
 *    ?: Matches exactly one character/*from www. ja  v a 2s  .  c  o m*/
 *
 *   Your search can include the literal values of the wildcard characters; you just need to escape
 *   them with a backslash before the character. For example, a value of \*amazon\?\\ searches for
 *   the literal string *amazon?\.
 *
 * Wildcards are translated for use with 'like':
 *
 *   % : Matches zero or more characters
 *   _: Matches exactly one character
 *
 * In both cases wildcards can be escaped (to allow literal values) with a backslash (\).
 *
 * Translation of wildcards for direct DB filtering must support literal values from each grammar.
 */
private Criterion buildRestriction(final String property, final Object persistentValue) {
    final Object valueObject;
    if (persistentValue instanceof String) {
        final String value = persistentValue.toString();
        final StringBuilder likeValueBuilder = new StringBuilder();
        translateWildcards(value, likeValueBuilder, "_", "%", SyntaxEscape.Like);
        final String likeValue = likeValueBuilder.toString();

        if (!value.equals(likeValue)) { // even if no regex, may contain \ escapes that must be removed
            return Restrictions.like(property, likeValue);
        }

        valueObject = persistentValue;
    } else {
        valueObject = persistentValue;
    }

    if (persistentValue instanceof Collection) {
        if (((Collection) persistentValue).isEmpty()) {
            return Restrictions.not(Restrictions.conjunction()); // always false
        } else {
            return Restrictions.in(property, (Collection) persistentValue);
        }
    } else {
        return Restrictions.eq(property, valueObject);
    }
}

From source file:com.eucalyptus.compute.common.internal.tags.Tags.java

License:Open Source License

/**
 * Count tags matching the given example and criteria.
 *
 * <p>The count will not include reserved tags.</p>
 *
 * @param example The tag example//from   ww w. ja v  a 2 s.c  o  m
 * @return The matching tag count.
 */
public static long count(final Tag example) {
    final EntityTransaction transaction = Entities.get(example);
    try {
        final Junction reservedTagKey = Restrictions.disjunction();
        reservedTagKey.add(Restrictions.like("displayName", "aws:%"));
        reservedTagKey.add(Restrictions.like("displayName", "euca:%"));
        return Entities.count(example, Restrictions.not(reservedTagKey),
                Collections.<String, String>emptyMap());
    } finally {
        transaction.rollback();
    }
}

From source file:com.eucalyptus.compute.common.internal.vm.VmInstances.java

License:Open Source License

/**
 * List instances that are not done and match the given owner/predicate.
 *
 * @param ownerFullName The owning user or account
 * @param predicate The predicate to match
 * @return The matching instances/*from   w  ww .  j a  v a  2  s . co m*/
 * @see com.eucalyptus.compute.common.internal.vm.VmInstance.VmStateSet#DONE
 */
public static List<VmInstance> list(@Nullable OwnerFullName ownerFullName,
        @Nullable Predicate<? super VmInstance> predicate) {
    return list(ownerFullName, Restrictions.not(VmInstance.criterion(VmInstance.VmStateSet.DONE.array())),
            Collections.<String, String>emptyMap(),
            Predicates.and(VmInstance.VmStateSet.DONE.not(), checkPredicate(predicate)), false);
}

From source file:com.eucalyptus.compute.service.ComputeService.java

License:Open Source License

public DescribeInstancesResponseType describeInstances(final DescribeInstancesType msg)
        throws EucalyptusCloudException {
    final DescribeInstancesResponseType reply = msg.getReply();
    Context ctx = Contexts.lookup();
    boolean showAll = msg.getInstancesSet().remove("verbose") || !msg.getInstancesSet().isEmpty();
    final Multimap<String, RunningInstancesItemType> instanceMap = TreeMultimap.create();
    final Map<String, ReservationInfoType> reservations = Maps.newHashMap();
    final Collection<String> identifiers = normalizeInstanceIdentifiers(msg.getInstancesSet());
    final Filter filter = Filters.generateFor(msg.getFilterSet(), VmInstance.class)
            .withOptionalInternalFilter("instance-id", identifiers).generate();
    final Filter persistenceFilter = getPersistenceFilter(VmInstance.class, identifiers, "instance-id", filter);
    final Predicate<? super VmInstance> requestedAndAccessible = CloudMetadatas.filteringFor(VmInstance.class)
            .byId(identifiers) // filters without wildcard support
            .byPredicate(filter.asPredicate()).byPrivileges().buildPredicate();
    final OwnerFullName ownerFullName = (ctx.isAdministrator() && showAll) ? null
            : ctx.getUserFullName().asAccountFullName();
    try (final TransactionResource db = Entities.readOnlyDistinctTransactionFor(VmInstance.class)) {
        final List<VmInstance> instances = VmInstances.list(ownerFullName,
                persistenceFilter.asCriterionWithConjunction(
                        Restrictions.not(VmInstance.criterion(VmInstance.VmState.BURIED))),
                persistenceFilter.getAliases(),
                Predicates.and(new TrackingPredicate<VmInstance>(identifiers), requestedAndAccessible));
        errorIfNotFound("InvalidInstanceID.NotFound", "instance ID", identifiers);
        final Map<String, List<Tag>> tagsMap = TagSupport.forResourceClass(VmInstance.class).getResourceTagMap(
                AccountFullName.getInstance(ctx.getAccountNumber()),
                Iterables.transform(instances, CloudMetadatas.toDisplayName()));

        for (final VmInstance vm : instances) {
            if (instanceMap.put(vm.getReservationId(), VmInstance.transform(vm))
                    && !reservations.containsKey(vm.getReservationId())) {
                reservations.put(vm.getReservationId(), TypeMappers.transform(vm, ReservationInfoType.class));
            }/*from   ww w . j a v a 2s  . com*/
        }
        List<ReservationInfoType> replyReservations = reply.getReservationSet();
        for (ReservationInfoType r : reservations.values()) {
            Collection<RunningInstancesItemType> instanceSet = instanceMap.get(r.getReservationId());
            if (!instanceSet.isEmpty()) {
                for (final RunningInstancesItemType instancesItemType : instanceSet) {
                    Tags.addFromTags(instancesItemType.getTagSet(), ResourceTag.class,
                            tagsMap.get(instancesItemType.getInstanceId()));
                }
                r.getInstancesSet().addAll(instanceSet);
                replyReservations.add(r);
            }
        }
    } catch (final Exception e) {
        Exceptions.findAndRethrow(e, ComputeServiceException.class);
        LOG.error(e);
        LOG.debug(e, e);
        throw new EucalyptusCloudException(e.getMessage());
    }
    return reply;
}

From source file:com.eucalyptus.compute.service.ComputeService.java

License:Open Source License

public DescribeInstanceStatusResponseType describeInstanceStatus(final DescribeInstanceStatusType msg)
        throws EucalyptusCloudException {
    final DescribeInstanceStatusResponseType reply = msg.getReply();
    final Context ctx = Contexts.lookup();
    final boolean showAll = msg.getInstancesSet().remove("verbose") || !msg.getInstancesSet().isEmpty();
    final boolean includeAllInstances = Objects.firstNonNull(msg.getIncludeAllInstances(), Boolean.FALSE);
    final Collection<String> identifiers = normalizeInstanceIdentifiers(msg.getInstancesSet());
    final Filter filter = Filters.generateFor(msg.getFilterSet(), VmInstance.class, "status")
            .withOptionalInternalFilter("instance-id", identifiers).generate();
    final Filter persistenceFilter = getPersistenceFilter(VmInstance.class, "status", identifiers,
            "instance-id", filter);
    final Predicate<? super VmInstance> requestedAndAccessible = CloudMetadatas.filteringFor(VmInstance.class)
            .byId(identifiers) // filters without wildcard support
            .byPredicate(includeAllInstances ? Predicates.<VmInstance>alwaysTrue() : VmInstance.VmState.RUNNING)
            .byPredicate(filter.asPredicate()).byPrivileges().buildPredicate();
    final OwnerFullName ownerFullName = (ctx.isAdministrator() && showAll) ? null
            : ctx.getUserFullName().asAccountFullName();
    try {/* w  w  w . j ava2s.c  om*/
        final List<VmInstance> instances = VmInstances.list(ownerFullName,
                persistenceFilter.asCriterionWithConjunction(
                        Restrictions.not(VmInstance.criterion(VmInstance.VmState.BURIED))),
                persistenceFilter.getAliases(),
                Predicates.and(new TrackingPredicate<VmInstance>(identifiers), requestedAndAccessible));
        errorIfNotFound("InvalidInstanceID.NotFound", "instance ID", identifiers);
        Iterables.addAll(reply.getInstanceStatusSet().getItem(), Iterables.transform(instances,
                TypeMappers.lookup(VmInstance.class, InstanceStatusItemType.class)));

    } catch (final Exception e) {
        Exceptions.findAndRethrow(e, ComputeServiceException.class);
        LOG.error(e);
        LOG.debug(e, e);
        throw new EucalyptusCloudException(e.getMessage());
    }
    return reply;
}

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

License:Open Source License

public ListBucketResponseType listBucket(ListBucketType request) throws EucalyptusCloudException {
    ListBucketResponseType reply = (ListBucketResponseType) request.getReply();

    EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class);

    try {/*from w w  w  .j  av  a 2  s  .co m*/
        String bucketName = request.getBucket();
        BucketInfo bucketInfo = new BucketInfo(bucketName);
        bucketInfo.setHidden(false);
        List<BucketInfo> bucketList = db.queryEscape(bucketInfo);

        Context ctx = Contexts.lookup();
        Account account = ctx.getAccount();

        int maxKeys = -1;
        String maxKeysString = request.getMaxKeys();
        if (maxKeysString != null) {
            maxKeys = Integer.parseInt(maxKeysString);
            if (maxKeys < 0) {
                throw new InvalidArgumentException("max-keys",
                        "Argument max-keys must be an integer between 0 and " + Integer.MAX_VALUE);
            }
        } else {
            maxKeys = WalrusProperties.MAX_KEYS;
        }

        if (bucketList.size() > 0) {
            BucketInfo bucket = bucketList.get(0);
            BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null;
            if (ctx.hasAdministrativePrivileges() || (bucket.canRead(account.getAccountNumber())
                    && (bucket.isGlobalRead() || Lookups.checkPrivilege(PolicySpec.S3_LISTBUCKET,
                            PolicySpec.VENDOR_S3, PolicySpec.S3_RESOURCE_BUCKET, bucketName, null)))) {
                if (logData != null) {
                    updateLogData(bucket, logData);
                    reply.setLogData(logData);
                }

                if (Contexts.lookup().hasAdministrativePrivileges()) {
                    try {
                        if (bucketHasSnapshots(bucketName)) {
                            db.rollback();
                            throw new NoSuchBucketException(bucketName);
                        }
                    } catch (Exception e) {
                        db.rollback();
                        throw new EucalyptusCloudException(e);
                    }
                }

                String prefix = request.getPrefix();
                String delimiter = request.getDelimiter();
                String marker = request.getMarker();

                reply.setName(bucketName);
                reply.setIsTruncated(false);
                reply.setPrefix(prefix);
                reply.setMarker(marker);
                reply.setDelimiter(delimiter);
                reply.setMaxKeys(maxKeys);

                if (maxKeys == 0) {
                    // No keys requested, so just return
                    reply.setContents(new ArrayList<ListEntry>());
                    reply.setCommonPrefixesList(new ArrayList<CommonPrefixesEntry>());
                    db.commit();
                    return reply;
                }

                final int queryStrideSize = maxKeys + 1;
                EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class);

                ObjectInfo searchObj = new ObjectInfo();
                searchObj.setBucketName(bucketName);
                searchObj.setLast(true);
                searchObj.setDeleted(false);

                Criteria objCriteria = dbObject.createCriteria(ObjectInfo.class);
                objCriteria.add(Example.create(searchObj));
                objCriteria.addOrder(Order.asc("objectKey"));
                objCriteria.setMaxResults(queryStrideSize); // add one to, hopefully, indicate truncation in one call

                if (!Strings.isNullOrEmpty(marker)) {
                    // The result set should be exclusive of the marker. marker could be a common prefix from a previous response. Look for keys that
                    // lexicographically follow the marker and don't contain the marker as the prefix.
                    objCriteria.add(Restrictions.and(Restrictions.gt("objectKey", marker),
                            Restrictions.not(Restrictions.like("objectKey", marker, MatchMode.START))));
                } else {
                    marker = "";
                }

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

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

                List<ObjectInfo> objectInfos = null;
                int resultKeyCount = 0;
                ArrayList<ListEntry> contents = new ArrayList<ListEntry>(); // contents for reply
                String nextMarker = null;
                TreeSet<String> commonPrefixes = new TreeSet<String>();
                int firstResult = -1;

                // Iterate over result sets of size maxkeys + 1
                do {
                    // Start listing from the 0th element and increment the first element to be listed by the query size
                    objCriteria.setFirstResult(queryStrideSize * (++firstResult));
                    objectInfos = (List<ObjectInfo>) objCriteria.list();

                    if (objectInfos.size() > 0) {
                        for (ObjectInfo objectInfo : objectInfos) {
                            String objectKey = objectInfo.getObjectKey();

                            // Check if it will get aggregated as a commonprefix
                            if (!Strings.isNullOrEmpty(delimiter)) {
                                String[] parts = objectKey.substring(prefix.length()).split(delimiter);
                                if (parts.length > 1) {
                                    String prefixString = prefix + parts[0] + delimiter;
                                    if (!commonPrefixes.contains(prefixString)) {
                                        if (resultKeyCount == maxKeys) {
                                            // This is a new record, so we know we're truncating if this is true
                                            reply.setNextMarker(nextMarker);
                                            reply.setIsTruncated(true);
                                            resultKeyCount++;
                                            break;
                                        }

                                        commonPrefixes.add(prefixString);
                                        resultKeyCount++; // count the unique commonprefix as a single return entry

                                        // If max keys have been collected, set the next-marker. It might be needed for the response if the list is
                                        // truncated
                                        // If the common prefixes hit the limit set by max-keys, next-marker is the last common prefix
                                        if (resultKeyCount == maxKeys) {
                                            nextMarker = prefixString;
                                        }
                                    }
                                    continue;
                                }
                            }

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

                            // Process the entry as a full key listing
                            ListEntry listEntry = new ListEntry();
                            listEntry.setKey(objectKey);
                            listEntry.setEtag(objectInfo.getEtag());
                            listEntry.setLastModified(DateUtils.format(objectInfo.getLastModified().getTime(),
                                    DateUtils.ALT_ISO8601_DATE_PATTERN));
                            listEntry.setStorageClass(objectInfo.getStorageClass());
                            listEntry.setSize(objectInfo.getSize());
                            listEntry.setStorageClass(objectInfo.getStorageClass());
                            try {
                                Account ownerAccount = Accounts.lookupAccountById(objectInfo.getOwnerId());
                                listEntry.setOwner(new CanonicalUserType(ownerAccount.getCanonicalId(),
                                        ownerAccount.getName()));
                            } catch (AuthException e) {
                                db.rollback();
                                throw new AccessDeniedException("Bucket", bucketName, logData);
                            }
                            contents.add(listEntry);

                            resultKeyCount++;

                            // If max keys have been collected, set the next-marker. It might be needed for the response if the list is truncated
                            if (resultKeyCount == maxKeys) {
                                nextMarker = objectKey;
                            }
                        }
                    }

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

                reply.setContents(contents);

                // Prefixes are already sorted, add them to the proper data structures and populate the reply
                if (!commonPrefixes.isEmpty()) {
                    ArrayList<CommonPrefixesEntry> commonPrefixesList = new ArrayList<CommonPrefixesEntry>();
                    for (String prefixEntry : commonPrefixes) {
                        commonPrefixesList.add(new CommonPrefixesEntry().add(new PrefixEntry(prefixEntry)));
                    }
                    reply.setCommonPrefixesList(commonPrefixesList);
                }
            } else {
                db.rollback();
                throw new AccessDeniedException("Bucket", bucketName, logData);
            }
        } else {
            db.rollback();
            throw new NoSuchBucketException(bucketName);
        }
        db.commit();
        return reply;
    } finally {
        if (db.isActive()) {
            db.rollback();
        }
    }
}

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

License:Open Source License

public ListVersionsResponseType listVersions(ListVersionsType request) throws EucalyptusCloudException {
    ListVersionsResponseType reply = (ListVersionsResponseType) request.getReply();

    EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class);

    try {// w w  w  .j  a  va2 s . c  o m
        String bucketName = request.getBucket();
        BucketInfo bucketInfo = new BucketInfo(bucketName);
        bucketInfo.setHidden(false);
        List<BucketInfo> bucketList = db.queryEscape(bucketInfo);

        Context ctx = Contexts.lookup();
        Account account = ctx.getAccount();

        int maxKeys = -1;
        String maxKeysString = request.getMaxKeys();
        if (maxKeysString != null) {
            maxKeys = Integer.parseInt(maxKeysString);
            if (maxKeys < 0) {
                throw new InvalidArgumentException("max-keys",
                        "Argument max-keys must be an integer between 0 and " + Integer.MAX_VALUE);
            }
        } else {
            maxKeys = WalrusProperties.MAX_KEYS;
        }

        if (bucketList.size() > 0) {
            BucketInfo bucket = bucketList.get(0);
            BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null;

            if (ctx.hasAdministrativePrivileges() || (bucket.canRead(account.getAccountNumber())
                    && (bucket.isGlobalRead() || Lookups.checkPrivilege(PolicySpec.S3_LISTBUCKETVERSIONS,
                            PolicySpec.VENDOR_S3, PolicySpec.S3_RESOURCE_BUCKET, bucketName, null)))) {

                if (logData != null) {
                    updateLogData(bucket, logData);
                    reply.setLogData(logData);
                }

                if (Contexts.lookup().hasAdministrativePrivileges()) {
                    try {
                        if (bucketHasSnapshots(bucketName)) {
                            db.rollback();
                            throw new NoSuchBucketException(bucketName);
                        }
                    } catch (Exception e) {
                        db.rollback();
                        throw new EucalyptusCloudException(e);
                    }
                }

                String prefix = request.getPrefix();
                String keyMarker = request.getKeyMarker();
                String versionMarker = request.getVersionIdMarker();
                String delimiter = request.getDelimiter();

                reply.setName(bucketName);
                reply.setIsTruncated(false);
                reply.setPrefix(prefix);
                reply.setMaxKeys(maxKeys);
                reply.setDelimiter(delimiter);
                reply.setKeyMarker(keyMarker);
                reply.setVersionIdMarker(versionMarker);

                if (bucket.isVersioningDisabled()) {
                    db.commit();
                    return reply;
                }

                if (maxKeys == 0) {
                    // No keys requested, so just return
                    reply.setKeyEntries(new ArrayList<KeyEntry>());
                    reply.setCommonPrefixesList(new ArrayList<CommonPrefixesEntry>());
                    db.commit();
                    return reply;
                }

                final int queryStrideSize = maxKeys + 1;
                EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class);

                ObjectInfo searchObj = new ObjectInfo();
                searchObj.setBucketName(bucketName);

                Criteria objCriteria = dbObject.createCriteria(ObjectInfo.class);
                objCriteria.add(Example.create(searchObj));
                objCriteria.addOrder(Order.asc("objectKey"));
                objCriteria.addOrder(Order.desc("lastModified"));
                objCriteria.setMaxResults(queryStrideSize); // add one to, hopefully, indicate truncation in one call

                // Ensure these aren't null
                keyMarker = (Strings.isNullOrEmpty(keyMarker) ? "" : keyMarker);
                prefix = (Strings.isNullOrEmpty(prefix) ? "" : prefix);
                versionMarker = (Strings.isNullOrEmpty(versionMarker) ? "" : versionMarker);

                if (!Strings.isNullOrEmpty(keyMarker)) {
                    if (!Strings.isNullOrEmpty(versionMarker)) {
                        Date resumeDate = null;
                        try {
                            ObjectInfo markerObj = new ObjectInfo();
                            markerObj.setBucketName(bucketName);
                            markerObj.setVersionId(versionMarker);
                            markerObj.setObjectKey(keyMarker);
                            ObjectInfo lastFromPrevObj = dbObject.uniqueResultEscape(markerObj);
                            if (lastFromPrevObj != null && lastFromPrevObj.getLastModified() != null) {
                                resumeDate = lastFromPrevObj.getLastModified();
                            } else {
                                dbObject.rollback();
                                throw new NoSuchEntityException("VersionIDMarker " + versionMarker
                                        + " does not match an existing object version");
                            }
                        } catch (TransactionException e) {
                            LOG.error(e);
                            dbObject.rollback();
                            throw new EucalyptusCloudException(
                                    "Next-Key-Marker or Next-Version-Id marker invalid");
                        }
                        // The result set should be exclusive of the key with the key-marker version-id-marker pair. Look for keys that lexicographically
                        // follow the version-id-marker for a given key-marker and also the keys that follow the key-marker.
                        objCriteria.add(Restrictions.or(
                                Restrictions.and(Restrictions.eq("objectKey", keyMarker),
                                        Restrictions.lt("lastModified", resumeDate)),
                                Restrictions.gt("objectKey", keyMarker)));
                    } else {
                        // The result set should be exclusive of the key-marker. key-marker could be a common prefix from a previous response. Look for keys
                        // that lexicographically follow the key-marker and don't contain the key-marker as the prefix.
                        objCriteria.add(Restrictions.and(Restrictions.gt("objectKey", keyMarker),
                                Restrictions.not(Restrictions.like("objectKey", keyMarker, MatchMode.START))));
                    }
                }

                if (!Strings.isNullOrEmpty(prefix)) {
                    objCriteria.add(Restrictions.like("objectKey", prefix, MatchMode.START));
                } else {
                    prefix = ""; // ensure not null has already been set in the reply, so this is safe
                }

                List<ObjectInfo> objectInfos = null;
                int resultKeyCount = 0;
                ArrayList<KeyEntry> keyEntries = new ArrayList<KeyEntry>();
                String nextKeyMarker = null;
                String nextVersionIdMarker = null;
                TreeSet<String> commonPrefixes = new TreeSet<String>();
                int firstResult = -1;

                // Iterate over result sets of size maxkeys + 1
                do {
                    // Start listing from the 0th element and increment the first element to be listed by the query size
                    objCriteria.setFirstResult(queryStrideSize * (++firstResult));
                    objectInfos = (List<ObjectInfo>) objCriteria.list();

                    if (objectInfos.size() > 0) {

                        for (ObjectInfo objectInfo : objectInfos) {
                            String objectKey = objectInfo.getObjectKey();

                            // Check if it will get aggregated as a commonprefix
                            if (!Strings.isNullOrEmpty(delimiter)) {
                                String[] parts = objectKey.substring(prefix.length()).split(delimiter);
                                if (parts.length > 1) {
                                    String prefixString = prefix + parts[0] + delimiter;
                                    if (!commonPrefixes.contains(prefixString)) {
                                        if (resultKeyCount == maxKeys) {
                                            // This is a new record, so we know we're truncating if this is true
                                            reply.setNextKeyMarker(nextKeyMarker);
                                            reply.setNextVersionIdMarker(nextVersionIdMarker);
                                            reply.setIsTruncated(true);
                                            resultKeyCount++;
                                            break;
                                        }

                                        commonPrefixes.add(prefixString);
                                        resultKeyCount++; // count the unique commonprefix as a single return entry

                                        // If max keys have been collected, set the next-key-marker. It might be needed for the response if the list is
                                        // truncated
                                        // If the common prefixes hit the limit set by max-keys, next-key-marker is the last common prefix and there is no
                                        // version-id-marker
                                        if (resultKeyCount == maxKeys) {
                                            nextKeyMarker = prefixString;
                                            nextVersionIdMarker = null;
                                        }
                                    }
                                    continue;
                                }
                            }

                            if (resultKeyCount == maxKeys) {
                                // This is a new (non-commonprefix) record, so we know we're truncating
                                reply.setNextKeyMarker(nextKeyMarker);
                                reply.setNextVersionIdMarker(nextVersionIdMarker);
                                reply.setIsTruncated(true);
                                resultKeyCount++;
                                break;
                            }

                            // This is either a version entry or a delete marker
                            KeyEntry keyEntry = null;
                            if (!objectInfo.getDeleted()) {
                                keyEntry = new VersionEntry();
                                ((VersionEntry) keyEntry).setEtag(objectInfo.getEtag());
                                ((VersionEntry) keyEntry).setSize(objectInfo.getSize());
                                ((VersionEntry) keyEntry).setStorageClass(objectInfo.getStorageClass());
                            } else {
                                keyEntry = new DeleteMarkerEntry();
                            }
                            keyEntry.setKey(objectKey);
                            keyEntry.setVersionId(objectInfo.getVersionId());
                            keyEntry.setIsLatest(objectInfo.getLast());
                            keyEntry.setLastModified(DateUtils.format(objectInfo.getLastModified().getTime(),
                                    DateUtils.ALT_ISO8601_DATE_PATTERN));
                            try {
                                Account ownerAccount = Accounts.lookupAccountById(objectInfo.getOwnerId());
                                keyEntry.setOwner(new CanonicalUserType(ownerAccount.getCanonicalId(),
                                        ownerAccount.getName()));
                            } catch (AuthException e) {
                                db.rollback();
                                throw new AccessDeniedException("Bucket", bucketName, logData);
                            }
                            keyEntries.add(keyEntry);

                            resultKeyCount++;

                            // If max keys have been collected, set the next- markers. They might be needed for the response if the list is truncated
                            if (resultKeyCount == maxKeys) {
                                nextKeyMarker = objectKey;
                                nextVersionIdMarker = objectInfo.getVersionId();
                            }
                        }
                    }
                    if (resultKeyCount <= maxKeys && objectInfos.size() <= maxKeys) {
                        break;
                    }
                } while (resultKeyCount <= maxKeys);

                reply.setKeyEntries(keyEntries);

                // Prefixes are already sorted, add them to the proper data structures and populate the reply
                if (!commonPrefixes.isEmpty()) {
                    ArrayList<CommonPrefixesEntry> commonPrefixesList = new ArrayList<CommonPrefixesEntry>();
                    for (String prefixEntry : commonPrefixes) {
                        commonPrefixesList.add(new CommonPrefixesEntry().add(new PrefixEntry(prefixEntry)));
                    }
                    reply.setCommonPrefixesList(commonPrefixesList);
                }
            } else {
                db.rollback();
                throw new AccessDeniedException("Bucket", bucketName, logData);
            }
        } else {
            db.rollback();
            throw new NoSuchBucketException(bucketName);
        }
        db.commit();
        return reply;
    } finally {
        if (db.isActive()) {
            db.rollback();
        }
    }
}

From source file:com.eucalyptus.vm.VmControl.java

License:Open Source License

public DescribeInstancesResponseType describeInstances(final DescribeInstancesType msg)
        throws EucalyptusCloudException {
    final DescribeInstancesResponseType reply = (DescribeInstancesResponseType) msg.getReply();
    Context ctx = Contexts.lookup();
    boolean showAll = msg.getInstancesSet().remove("verbose");
    final Multimap<String, RunningInstancesItemType> instanceMap = TreeMultimap.create();
    final Map<String, ReservationInfoType> reservations = Maps.newHashMap();
    final Collection<String> identifiers = normalizeIdentifiers(msg.getInstancesSet());
    final Filter filter = Filters.generateFor(msg.getFilterSet(), VmInstance.class)
            .withOptionalInternalFilter("instance-id", identifiers).generate();
    final Predicate<? super VmInstance> requestedAndAccessible = CloudMetadatas.filteringFor(VmInstance.class)
            .byId(identifiers) // filters without wildcard support
            .byPredicate(filter.asPredicate()).byPrivileges().buildPredicate();
    final Criterion criterion = filter
            .asCriterionWithConjunction(Restrictions.not(VmInstances.criterion(VmState.BURIED)));
    final OwnerFullName ownerFullName = (ctx.isAdministrator() && showAll) ? null
            : ctx.getUserFullName().asAccountFullName();
    try (final TransactionResource db = Entities.transactionFor(VmInstance.class)) {
        final List<VmInstance> instances = VmInstances.list(ownerFullName, criterion, filter.getAliases(),
                requestedAndAccessible);
        final Map<String, List<Tag>> tagsMap = TagSupport.forResourceClass(VmInstance.class).getResourceTagMap(
                AccountFullName.getInstance(ctx.getAccount()),
                Iterables.transform(instances, CloudMetadatas.toDisplayName()));

        for (final VmInstance vm : instances) {
            if (instanceMap.put(vm.getReservationId(), VmInstances.transform(vm))
                    && !reservations.containsKey(vm.getReservationId())) {
                reservations.put(vm.getReservationId(), TypeMappers.transform(vm, ReservationInfoType.class));
            }//  w w  w . j  a  v a2  s.co  m
        }
        List<ReservationInfoType> replyReservations = reply.getReservationSet();
        for (ReservationInfoType r : reservations.values()) {
            Collection<RunningInstancesItemType> instanceSet = instanceMap.get(r.getReservationId());
            if (!instanceSet.isEmpty()) {
                for (final RunningInstancesItemType instancesItemType : instanceSet) {
                    Tags.addFromTags(instancesItemType.getTagSet(), ResourceTag.class,
                            tagsMap.get(instancesItemType.getInstanceId()));
                }
                r.getInstancesSet().addAll(instanceSet);
                replyReservations.add(r);
            }
        }
    } catch (final Exception e) {
        LOG.error(e);
        LOG.debug(e, e);
        throw new EucalyptusCloudException(e.getMessage());
    }
    return reply;
}