Example usage for org.hibernate.criterion Restrictions disjunction

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

Introduction

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

Prototype

public static Disjunction disjunction() 

Source Link

Document

Group expressions together in a single disjunction (A or B or C...).

Usage

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) {// ww w .j  a va  2 s .c  o  m
    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);
        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.cloudwatch.domain.alarms.AlarmManager.java

License:Open Source License

private static boolean modifySelectedAlarms(final String accountId, final Collection<String> alarmNames,
        final Predicate<CloudWatchMetadata.AlarmMetadata> filter, final Predicate<AlarmEntity> update) {
    final Map<String, Collection<String>> accountToNamesMap = buildAccountIdToAlarmNamesMap(accountId,
            alarmNames);/*from   w w w  .  ja v a  2 s  . c  o  m*/
    final EntityTransaction db = Entities.get(AlarmEntity.class);
    try {
        final Criteria criteria = Entities.createCriteria(AlarmEntity.class);
        final Junction disjunction = Restrictions.disjunction();
        for (final Map.Entry<String, Collection<String>> entry : accountToNamesMap.entrySet()) {
            final Junction conjunction = Restrictions.conjunction();
            conjunction.add(Restrictions.eq("accountId", entry.getKey()));
            conjunction.add(Restrictions.in("alarmName", entry.getValue()));
            disjunction.add(conjunction);
        }
        criteria.add(disjunction);
        criteria.addOrder(Order.asc("creationTimestamp"));
        criteria.addOrder(Order.asc("naturalId"));
        final Collection<AlarmEntity> alarmEntities = (Collection<AlarmEntity>) criteria.list();
        if (!Iterables.all(alarmEntities, filter)) {
            return false;
        }
        CollectionUtils.each(alarmEntities, update);
        db.commit();
        return true;
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:com.eucalyptus.cloudwatch.domain.alarms.AlarmManager.java

License:Open Source License

public static List<AlarmEntity> describeAlarms(@Nullable final String accountId,
        @Nullable final String actionPrefix, @Nullable final String alarmNamePrefix,
        @Nullable final Collection<String> alarmNames, @Nullable final Integer maxRecords,
        @Nullable final StateValue stateValue, @Nullable final String nextToken,
        final Predicate<CloudWatchMetadata.AlarmMetadata> filter) throws CloudWatchException {
    final List<AlarmEntity> results = Lists.newArrayList();
    final EntityTransaction db = Entities.get(AlarmEntity.class);
    try {//  w  w w  . ja  v a  2 s .  c  om
        boolean first = true;
        String token = nextToken;
        while (token != null || first) {
            first = false;
            final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmEntity.class,
                    true);
            final Criteria criteria = Entities.createCriteria(AlarmEntity.class);
            if (accountId != null) {
                criteria.add(Restrictions.eq("accountId", accountId));
            }
            if (actionPrefix != null) {
                final Junction actionsOf = Restrictions.disjunction();
                for (int i = 1; i <= AlarmEntity.MAX_OK_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("okAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                for (int i = 1; i <= AlarmEntity.MAX_ALARM_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("alarmAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                for (int i = 1; i <= AlarmEntity.MAX_INSUFFICIENT_DATA_ACTIONS_NUM; i++) {
                    actionsOf.add(Restrictions.like("insufficientDataAction" + i, actionPrefix + "%")); // May need Restrictions.ilike for case insensitive
                }
                criteria.add(actionsOf);
            }
            if (alarmNamePrefix != null) {
                criteria.add(Restrictions.like("alarmName", alarmNamePrefix + "%"));
            }
            if (alarmNames != null && !alarmNames.isEmpty()) {
                criteria.add(Restrictions.in("alarmName", alarmNames));
            }
            if (stateValue != null) {
                criteria.add(Restrictions.eq("stateValue", stateValue));
            }
            NextTokenUtils.addNextTokenConstraints(maxRecords == null ? null : maxRecords - results.size(),
                    token, nextTokenCreatedTime, criteria);
            final List<AlarmEntity> alarmEntities = (List<AlarmEntity>) criteria.list();
            Iterables.addAll(results, Iterables.filter(alarmEntities, filter));
            token = maxRecords == null || (maxRecords != null
                    && (results.size() >= maxRecords || alarmEntities.size() < maxRecords)) ? null
                            : alarmEntities.get(alarmEntities.size() - 1).getNaturalId();
        }
        db.commit();
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
    return results;
}

From source file:com.eucalyptus.cloudwatch.domain.alarms.AlarmManager.java

License:Open Source License

public static List<AlarmHistory> describeAlarmHistory(@Nullable final String accountId,
        @Nullable final String alarmName, @Nullable final Date endDate,
        @Nullable final HistoryItemType historyItemType, @Nullable final Integer maxRecords,
        @Nullable final Date startDate, @Nullable final String nextToken, final Predicate<AlarmHistory> filter)
        throws CloudWatchException {
    final List<AlarmHistory> results = Lists.newArrayList();
    final EntityTransaction db = Entities.get(AlarmHistory.class);
    try {//from w  w  w .  ja v  a  2  s  . c  om
        final Map<String, Collection<String>> accountToNamesMap = alarmName == null
                ? Collections.<String, Collection<String>>emptyMap()
                : buildAccountIdToAlarmNamesMap(accountId, Collections.singleton(alarmName));
        boolean first = true;
        String token = nextToken;
        while (token != null || first) {
            first = false;
            final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmHistory.class,
                    true);
            final Criteria criteria = Entities.createCriteria(AlarmHistory.class);
            final Junction disjunction = Restrictions.disjunction();
            for (final Map.Entry<String, Collection<String>> entry : accountToNamesMap.entrySet()) {
                final Junction conjunction = Restrictions.conjunction();
                conjunction.add(Restrictions.eq("accountId", entry.getKey()));
                conjunction.add(Restrictions.in("alarmName", entry.getValue()));
                disjunction.add(conjunction);
            }
            criteria.add(disjunction);
            if (historyItemType != null) {
                criteria.add(Restrictions.eq("historyItemType", historyItemType));
            }
            if (startDate != null) {
                criteria.add(Restrictions.ge("timestamp", startDate));
            }
            if (endDate != null) {
                criteria.add(Restrictions.le("timestamp", endDate));
            }
            NextTokenUtils.addNextTokenConstraints(maxRecords == null ? null : maxRecords - results.size(),
                    token, nextTokenCreatedTime, criteria);
            final List<AlarmHistory> alarmHistoryEntities = (List<AlarmHistory>) criteria.list();
            Iterables.addAll(results, Iterables.filter(alarmHistoryEntities, filter));
            token = maxRecords == null || (maxRecords != null
                    && (results.size() >= maxRecords || alarmHistoryEntities.size() < maxRecords)) ? null
                            : alarmHistoryEntities.get(alarmHistoryEntities.size() - 1).getNaturalId();
        }
        db.commit();
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
    return results;
}

From source file:com.eucalyptus.cloudwatch.domain.listmetrics.ListMetricManager.java

License:Open Source License

/**
 * Returns the metrics that are associated with the applied parameters
 * @param accountId the account Id.  If null, this filter will not be used.
 * @param metricName the metric name.  If null, this filter will not be used.
 * @param namespace the namespace.  If null, this filter will not be used.
 * @param dimensionMap the dimensions (name/value) to filter against.  Only metrics containing all these dimensions will be returned (it is only a subset match, not exact).  If null, this filter will not be used.
 * @param after the time after which all metrics must have been updated (last seen).  If null, this filter will not be used.
 * @param before the time before which all metrics must have been updated (last seen). If null, this filter will not be used.
 * @param maxRecords TODO/*ww w .j  av  a 2 s  . c om*/
 * @param nextToken TODO
 * @return the collection of metrics, filtered by the input
 */
public static List<ListMetric> listMetrics(String accountId, String metricName, String namespace,
        Map<String, String> dimensionMap, Date after, Date before, Integer maxRecords, String nextToken)
        throws CloudWatchException {
    if (dimensionMap != null && dimensionMap.size() > ListMetric.MAX_DIM_NUM) {
        throw new IllegalArgumentException("Too many dimensions " + dimensionMap.size());
    }
    EntityTransaction db = Entities.get(ListMetric.class);
    try {
        Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(nextToken, ListMetric.class, false);
        Map<String, String> sortedDimensionMap = new TreeMap<String, String>();
        Criteria criteria = Entities.createCriteria(ListMetric.class);
        if (accountId != null) {
            criteria = criteria.add(Restrictions.eq("accountId", accountId));
        }
        if (metricName != null) {
            criteria = criteria.add(Restrictions.eq("metricName", metricName));
        }
        if (namespace != null) {
            criteria = criteria.add(Restrictions.eq("namespace", namespace));
        }
        if (before != null) {
            criteria = criteria.add(Restrictions.le("lastUpdateTimestamp", before));
        }
        if (after != null) {
            criteria = criteria.add(Restrictions.ge("lastUpdateTimestamp", after));
        }
        if (dimensionMap != null && !dimensionMap.isEmpty()) {
            // sort the map 
            sortedDimensionMap.putAll(dimensionMap);
            // now we are going to add a bunch of restrictions to the criteria...
            // note though there are certain dimensions we don't need to check.
            // For example if we have two dimensions, we don't need to check dimension 10 for
            // the first item or dimension 1 for the last item.
            int numDimensions = sortedDimensionMap.size();
            int lowDimNum = 1;
            int highDimNum = ListMetric.MAX_DIM_NUM + 1 - numDimensions;
            for (Map.Entry<String, String> dimEntry : sortedDimensionMap.entrySet()) {
                Disjunction or = Restrictions.disjunction();
                for (int i = lowDimNum; i <= highDimNum; i++) {
                    or.add(Restrictions.conjunction()
                            .add(Restrictions.eq("dim" + i + "Name", dimEntry.getKey()))
                            .add(Restrictions.eq("dim" + i + "Value", dimEntry.getValue())));
                }
                lowDimNum++;
                highDimNum++;
                criteria = criteria.add(or);
            }
        }
        criteria = NextTokenUtils.addNextTokenConstraints(maxRecords, nextToken, nextTokenCreatedTime,
                criteria);
        List<ListMetric> dbResult = (List<ListMetric>) criteria.list();
        db.commit();
        return dbResult;
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

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/*from w w w.  j  a v a  2  s. co 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.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/*  w w  w  . j a 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.service.ComputeService.java

License:Open Source License

/**
 *
 *//*from   w w  w  .jav a  2s . c  o m*/
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.simpleworkflow.persist.PersistenceWorkflowExecutions.java

License:Open Source License

public <T> List<T> listTimedOut(final long time, final Function<? super WorkflowExecution, T> transform)
        throws SwfMetadataException {
    return listByExample(WorkflowExecution.exampleForOpenWorkflow(), Predicates.alwaysTrue(),
            Restrictions.disjunction().add(Restrictions.lt("timeoutTimestamp", new Date(time)))
                    .add(Restrictions.lt("creationTimestamp",
                            new Date(time - getWorkflowExecutionDurationMillis()))),
            Collections.<String, String>emptyMap(), transform);
}

From source file:com.eucalyptus.simpleworkflow.persist.PersistenceWorkflowExecutions.java

License:Open Source License

public <T> List<T> listRetentionExpired(final long time, final Function<? super WorkflowExecution, T> transform)
        throws SwfMetadataException {
    return listByExample(WorkflowExecution.exampleForClosedWorkflow(), Predicates.alwaysTrue(),
            Restrictions.disjunction().add(Restrictions.lt("retentionTimestamp", new Date(time)))
                    .add(Restrictions.lt("closeTimestamp",
                            new Date(time - getWorkflowExecutionRetentionDurationMillis()))),
            Collections.<String, String>emptyMap(), transform);
}