Example usage for org.hibernate.criterion Restrictions conjunction

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

Introduction

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

Prototype

public static Conjunction conjunction() 

Source Link

Document

Group expressions together in a single conjunction (A and B and C...).

Usage

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

License:Open Source License

Filter(@Nonnull final Predicate<Object> predicate, final boolean filteringOnTags) {
    this(Collections.<String, String>emptyMap(), Restrictions.conjunction(), predicate, filteringOnTags);
}

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

License:Open Source License

/**
 * Filter as a Hibernate Criterion.//w  ww. j  ava2s.  com
 *
 * @param criterion
 * @return The criterion
 */
@Nonnull
public Criterion asCriterionWithConjunction(final Criterion criterion) {
    return Restrictions.conjunction().add(criterion).add(asCriterion());
}

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

License:Open Source License

/**
 * Combine filters./*w  w w .  ja  v  a 2  s  .  c  o m*/
 *
 * @param filter The filter to combine with
 * @return The new filter
 */
public Filter and(final Filter filter) {
    final Map<String, String> aliases = Maps.newHashMap();
    aliases.putAll(this.aliases);
    aliases.putAll(filter.aliases);
    final Junction and = Restrictions.conjunction();
    and.add(this.criterion);
    and.add(filter.criterion);
    return new Filter(aliases, and, Predicates.and(this.predicate, filter.predicate),
            this.filteringOnTags || filter.filteringOnTags);
}

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

License:Open Source License

/**
 * Generate a Filter for the given filters.
 *
 * @param filters The map of filter names to (multiple) values
 * @param allowInternalFilters True to allow use of internal filters
 * @return The filter representation// w w  w.jav a2  s .  c  o m
 * @throws InvalidFilterException If a filter is invalid
 */
public Filter generate(final Map<String, Set<String>> filters, final boolean allowInternalFilters,
        final String accountId) throws InvalidFilterException {
    // Construct collection filter
    final List<Predicate<Object>> and = Lists.newArrayList();
    for (final Map.Entry<String, Set<String>> filter : Iterables.filter(filters.entrySet(),
            Predicates.not(isTagFilter()))) {
        final List<Predicate<Object>> or = Lists.newArrayList();
        for (final String value : filter.getValue()) {
            final Function<? super String, Predicate<? super RT>> predicateFunction = predicateFunctions
                    .get(filter.getKey());
            if (predicateFunction == null
                    || (!allowInternalFilters && internalFilters.contains(filter.getKey()))) {
                throw InvalidFilterException.forName(filter.getKey());
            }
            final Predicate<? super RT> valuePredicate = predicateFunction.apply(value);
            or.add(typedPredicate(valuePredicate));
        }
        and.add(Predicates.or(or));
    }

    // Construct database filter and aliases
    final Junction conjunction = Restrictions.conjunction();
    final Map<String, String> aliases = Maps.newHashMap();
    for (final Map.Entry<String, Set<String>> filter : Iterables.filter(filters.entrySet(),
            Predicates.not(isTagFilter()))) {
        final Junction disjunction = Restrictions.disjunction();
        for (final String value : filter.getValue()) {
            final PersistenceFilter persistenceFilter = persistenceFilters.get(filter.getKey());
            if (persistenceFilter != null) {
                final Object persistentValue = persistenceFilter.value(value);
                if (persistentValue != null) {
                    for (final String alias : persistenceFilter.getAliases())
                        aliases.put(alias, this.aliases.get(alias));
                    disjunction.add(buildRestriction(persistenceFilter.getProperty(), persistentValue));
                } // else, there is no valid DB filter for the given value (e.g. wildcard for integer value)
            }
        }
        conjunction.add(disjunction);
    }

    // Construct database filter and aliases for tags
    boolean tagPresent = false;
    final List<Junction> tagJunctions = Lists.newArrayList();
    for (final Map.Entry<String, Set<String>> filter : Iterables.filter(filters.entrySet(), isTagFilter())) {
        tagPresent = true;
        final Junction disjunction = Restrictions.disjunction();
        final String filterName = filter.getKey();
        for (final String value : filter.getValue()) {
            if ("tag-key".equals(filterName)) {
                disjunction.add(buildTagRestriction(value, null, true));
            } else if ("tag-value".equals(filterName)) {
                disjunction.add(buildTagRestriction(null, value, true));
            } else {
                disjunction.add(buildTagRestriction(filterName.substring(4), value, false));
            }
        }
        tagJunctions.add(disjunction);
    }
    if (tagPresent)
        conjunction.add(tagCriterion(accountId, tagJunctions));

    return new Filter(aliases, conjunction, Predicates.and(and), tagPresent);
}

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/*  w  w w.  j  a  v a2s  .  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.FilterSupport.java

License:Open Source License

/**
 * Build a criterion that uses sub-selects to match the given tag restrictions
 *///ww  w  .  jav a  2s .c  o m
private Criterion tagCriterion(final String accountId, final List<Junction> junctions) {
    final Junction conjunction = Restrictions.conjunction();

    for (final Junction criterion : junctions) {
        final DetachedCriteria criteria = DetachedCriteria.forClass(tagClass)
                .add(Restrictions.eq("ownerAccountNumber", accountId)).add(criterion)
                .setProjection(Projections.property(resourceFieldName));
        conjunction.add(Property.forName(tagFieldName).in(criteria));
    }

    return conjunction;
}

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

License:Open Source License

/**
 * Build a restriction for a tag key and/or value.
 *//*from   w  w  w  .j  av a2 s.co m*/
private Criterion buildTagRestriction(@Nullable final String key, @Nullable final String value,
        final boolean keyWildcards) {

    final Junction criteria = Restrictions.conjunction();

    if (key != null) {
        criteria.add(keyWildcards ? buildRestriction("displayName", key) : Restrictions.eq("displayName", key));
    }

    if (value != null) {
        criteria.add(buildRestriction("value", value));
    }

    return criteria;
}

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

License:Open Source License

/**
 * Get the tags for the given resources, grouped by ID and ordered for display.
 * /*from   w  ww  .  j  a v a 2 s.  co m*/
 * @param owner The account for the tags
 * @param identifiers The resource identifiers for the tags
 * @return The tag map with an entry for each requested resource
 */
public Map<String, List<Tag>> getResourceTagMap(final OwnerFullName owner, final Iterable<String> identifiers) {
    final int identifiersSize = Iterables.size(identifiers);
    final Map<String, List<Tag>> tagMap = Maps.newHashMapWithExpectedSize(identifiersSize);
    for (final String id : identifiers) {
        tagMap.put(id, Lists.<Tag>newArrayList());
    }
    if (!tagMap.isEmpty()) {
        final Tag example = example(owner);
        final Criterion idRestriction = identifiersSize < 1000 ? Property.forName(tagClassResourceField)
                .in(DetachedCriteria.forClass(resourceClass)
                        .add(Restrictions.in(resourceClassIdField, Lists.newArrayList(identifiers)))
                        .setProjection(Projections.id()))
                : Restrictions.conjunction();
        try {
            final List<Tag> tags = Tags.list(example, Predicates.alwaysTrue(), idRestriction,
                    Collections.<String, String>emptyMap());
            for (final Tag tag : tags) {
                final List<Tag> keyTags = tagMap.get(tag.getResourceId());
                if (keyTags != null) {
                    keyTags.add(tag);
                }
            }
        } catch (Exception e) {
            log.error(e, e);
        }
        Ordering<Tag> order = Ordering.natural().onResultOf(Tags.key());
        for (final String id : identifiers) {
            Collections.sort(tagMap.get(id), order);
        }
    }
    return tagMap;
}

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

License:Open Source License

/**
 *
 *///from   www  .  ja  v a  2 s  .  c om
public DescribeVolumesResponseType describeVolumes(DescribeVolumesType request) throws Exception {
    final DescribeVolumesResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    final boolean showAll = request.getVolumeSet().remove("verbose");
    final Set<String> volumeIds = Sets.newLinkedHashSet(normalizeVolumeIdentifiers(request.getVolumeSet()));
    final AccountFullName ownerFullName = (ctx.isAdministrator() && (showAll || !volumeIds.isEmpty())) ? null
            : ctx.getUserFullName().asAccountFullName();

    final Filters.FiltersBuilder filtersBuilder = Filters.generateFor(request.getFilterSet(), Volume.class);
    if (!ctx.isAdministrator()) {
        filtersBuilder.withOptionalInternalFilter("system-managed", Collections.singleton("false"));
    }
    final Filter filter = filtersBuilder.generate();
    final Filter persistenceFilter = getPersistenceFilter(Volume.class, volumeIds, "volume-id", filter);
    final Predicate<? super Volume> requestedAndAccessible = CloudMetadatas.filteringFor(Volume.class)
            .byId(volumeIds).byPredicate(filter.asPredicate()).byPrivileges().buildPredicate();

    final Function<Set<String>, Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>>> populateVolumeSet = new Function<Set<String>, Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>>>() {
        public Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>> apply(
                final Set<String> input) {
            final Set<String> allowedVolumeIds = Sets.newHashSet();
            final ArrayList<com.eucalyptus.compute.common.Volume> replyVolumes = Lists.newArrayList();
            final List<Volume> volumes = Entities.query(Volume.named(ownerFullName, null), true,
                    persistenceFilter.asCriterion(), persistenceFilter.getAliases());
            final Iterable<Volume> filteredVolumes = Iterables.filter(volumes,
                    Predicates.and(new TrackingPredicate<Volume>(volumeIds), requestedAndAccessible));

            // load attachment info
            final Criterion attachmentCriterion;
            final Map<String, String> attachmentAliases;
            if (Iterables.isEmpty(filteredVolumes)) {
                attachmentCriterion = Restrictions.disjunction();
                attachmentAliases = Collections.emptyMap();
            } else if (Iterables.size(Iterables.limit(filteredVolumes, 51)) < 50) { // small # load by id
                attachmentCriterion = Restrictions.in("volumeId",
                        Sets.newHashSet(Iterables.transform(filteredVolumes, RestrictedTypes.toDisplayName())));
                attachmentAliases = Collections.emptyMap();
            } else if (ownerFullName == null) { // load attachments for all accounts
                attachmentCriterion = Restrictions.conjunction();
                attachmentAliases = Collections.emptyMap();
            } else { // load all attachments for account
                attachmentCriterion = Restrictions.eq("vmInstance.ownerAccountNumber",
                        ownerFullName.getAccountNumber());
                ;
                attachmentAliases = Collections.singletonMap("vmInstance", "vmInstance");
            }
            final Map<String, VmVolumeAttachment> attachmentMap = CollectionUtils.putAll(
                    Iterables.concat(
                            Entities.query(VmBootVolumeAttachment.example(), true, attachmentCriterion,
                                    attachmentAliases),
                            Entities.query(VmStandardVolumeAttachment.example(), true, attachmentCriterion,
                                    attachmentAliases)),
                    Maps.<String, VmVolumeAttachment>newHashMap(), VmVolumeAttachment.volumeId(),
                    Functions.<VmVolumeAttachment>identity());

            // build response volumes
            for (final Volume foundVol : filteredVolumes) {
                allowedVolumeIds.add(foundVol.getDisplayName());
                if (State.ANNIHILATED.equals(foundVol.getState())) {
                    Entities.delete(foundVol);
                    replyVolumes.add(foundVol.morph(new com.eucalyptus.compute.common.Volume()));
                } else {
                    VmVolumeAttachment attachment = attachmentMap.get(foundVol.getDisplayName());
                    AttachedVolume attachedVolume = null;
                    if (attachment != null) {
                        attachedVolume = VmVolumeAttachment.asAttachedVolume(attachment.getVmInstance())
                                .apply(attachment);
                    } else {
                        if (State.BUSY.equals(foundVol.getState())) {
                            foundVol.setState(State.EXTANT);
                        }
                    }
                    com.eucalyptus.compute.common.Volume msgTypeVolume = foundVol
                            .morph(new com.eucalyptus.compute.common.Volume());
                    if (attachedVolume != null) {
                        msgTypeVolume.setStatus("in-use");
                        msgTypeVolume.getAttachmentSet().add(attachedVolume);
                    }
                    replyVolumes.add(msgTypeVolume);
                }
            }
            return Pair.pair(allowedVolumeIds, replyVolumes);
        }
    };

    final Pair<Set<String>, ArrayList<com.eucalyptus.compute.common.Volume>> volumeIdsAndVolumes = Entities
            .asTransaction(Volume.class, populateVolumeSet).apply(volumeIds);
    errorIfNotFound("InvalidVolume.NotFound", "volume", volumeIds);
    @SuppressWarnings("ConstantConditions")
    final Set<String> allowedVolumeIds = volumeIdsAndVolumes.getLeft();
    reply.setVolumeSet(volumeIdsAndVolumes.getRight());

    Map<String, List<Tag>> tagsMap = TagSupport.forResourceClass(Volume.class)
            .getResourceTagMap(AccountFullName.getInstance(ctx.getAccountNumber()), allowedVolumeIds);
    for (final com.eucalyptus.compute.common.Volume volume : reply.getVolumeSet()) {
        Tags.addFromTags(volume.getTagSet(), ResourceTag.class, tagsMap.get(volume.getVolumeId()));
    }

    return reply;
}

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

License:Open Source License

/**
 * Count the matching entities for the given example.
 * /*  w w  w .  ja  va 2s .  c o m*/
 * @param example The example entity
 * @return The number of matching entities
 */
public static long count(final Object example) {
    return count(example, Restrictions.conjunction(), Collections.<String, String>emptyMap());
}