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.ephesoft.dcma.da.dao.hibernate.BatchInstanceGroupsDaoImpl.java

License:Open Source License

/**
 * API for getting the batch instance identifiers except provided user roles.
 * /*from  www.  ja va2s.co  m*/
 * @param userRoles Set<String>
 * @return Set<String>
 */
@Override
public Set<String> getBatchInstanceIdentifiersExceptUserRoles(final Set<String> userRoles) {
    Set<String> batchInstanceIdentifiers = new HashSet<String>();
    final DetachedCriteria criteria = criteria();
    final Disjunction disjunction = Restrictions.disjunction();
    disjunction.add(Restrictions.not(Restrictions.in(GROUP_NAME, userRoles)));
    criteria.add(disjunction);
    final List<BatchInstanceGroups> batchInstanceGroups = find(criteria);
    for (final BatchInstanceGroups batchInstanceGroup : batchInstanceGroups) {
        batchInstanceIdentifiers.add(batchInstanceGroup.getBatchInstanceIdentifier());
    }
    return batchInstanceIdentifiers;
}

From source file:com.eryansky.common.orm.core.hibernate.restriction.CriterionMultipleValueSupport.java

License:Apache License

public Criterion build(PropertyFilter filter) {
    Object value = convertMatchValue(filter.getMatchValue(), filter.getFieldType());
    Criterion criterion = null;/*from   w  w  w .  j av  a  2  s  .co m*/
    if (filter.hasMultiplePropertyNames()) {
        Disjunction disjunction = Restrictions.disjunction();
        for (String propertyName : filter.getPropertyNames()) {
            disjunction.add(build(propertyName, value));
        }
        criterion = disjunction;
    } else {
        criterion = build(filter.getSinglePropertyName(), value);
    }
    return criterion;
}

From source file:com.eryansky.common.orm.core.hibernate.restriction.CriterionSingleValueSupport.java

License:Apache License

public Criterion build(PropertyFilter filter) {
    String matchValue = filter.getMatchValue();
    Class<?> FieldType = filter.getFieldType();

    MatchValue matchValueModel = getMatchValue(matchValue, FieldType);

    Junction criterion = null;//from w  w  w  . j  a  v  a2 s  . c o  m

    if (matchValueModel.hasOrOperate()) {
        criterion = Restrictions.disjunction();
    } else {
        criterion = Restrictions.conjunction();
    }

    for (Object value : matchValueModel.getValues()) {

        if (filter.hasMultiplePropertyNames()) {
            List<Criterion> disjunction = new ArrayList<Criterion>();
            for (String propertyName : filter.getPropertyNames()) {
                disjunction.add(build(propertyName, value));
            }
            criterion.add(Restrictions.or(disjunction.toArray(new Criterion[disjunction.size()])));
        } else {
            criterion.add(build(filter.getSinglePropertyName(), value));
        }

    }

    return criterion;
}

From source file:com.eucalyptus.autoscaling.common.internal.groups.PersistenceAutoScalingGroups.java

License:Open Source License

@Override
public <T> List<T> listRequiringMonitoring(final Set<MonitoringSelector> selectors,
        final Function<? super AutoScalingGroup, T> transform) throws AutoScalingMetadataException {
    final Collection<String> suffixes = selectors.stream()
            .flatMap(FUtils.chain(MonitoringSelector::suffixes, Collection::stream))
            .collect(Collectors.toSet());

    final Junction likeAnyOf = Restrictions.disjunction();
    for (final String suffix : suffixes) {
        likeAnyOf.add(Restrictions.ilike("id", "%" + suffix));
    }/*from w w w .j  av  a  2 s.  c o  m*/

    return persistenceSupport.listByExample(AutoScalingGroup.withOwner(null), Predicates.alwaysTrue(),
            likeAnyOf, Collections.<String, String>emptyMap(), transform);
}

From source file:com.eucalyptus.autoscaling.groups.PersistenceAutoScalingGroups.java

License:Open Source License

@Override
public <T> List<T> listRequiringMonitoring(final long interval,
        final Function<? super AutoScalingGroup, T> transform) throws AutoScalingMetadataException {
    // We want to select some groups depending on the interval / time 
    int group = (int) ((System.currentTimeMillis() / interval) % 6);

    final Collection<String> suffixes = Lists.newArrayList();
    switch (group) {
    case 0://  w w w .  ja v a  2s.c  o m
        suffixes.add("0");
        suffixes.add("1");
        suffixes.add("2");
        break;
    case 1:
        suffixes.add("3");
        suffixes.add("4");
        suffixes.add("5");
        break;
    case 2:
        suffixes.add("6");
        suffixes.add("7");
        suffixes.add("8");
        break;
    case 3:
        suffixes.add("9");
        suffixes.add("a");
        suffixes.add("b");
        break;
    case 4:
        suffixes.add("c");
        suffixes.add("d");
        break;
    default:
        suffixes.add("e");
        suffixes.add("f");
        break;
    }

    final Junction likeAnyOf = Restrictions.disjunction();
    for (final String suffix : suffixes) {
        likeAnyOf.add(Restrictions.ilike("id", "%" + suffix));
    }

    return persistenceSupport.listByExample(AutoScalingGroup.withOwner(null), Predicates.alwaysTrue(),
            likeAnyOf, Collections.<String, String>emptyMap(), transform);
}

From source file:com.eucalyptus.cloudwatch.common.internal.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);/*  ww  w .j  a  v  a2 s . com*/
    try (final TransactionResource db = Entities.transactionFor(AlarmEntity.class)) {
        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;
    }
}

From source file:com.eucalyptus.cloudwatch.common.internal.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<? super CloudWatchMetadata.AlarmMetadata> filter) throws InvalidTokenException {
    final List<AlarmEntity> results = Lists.newArrayList();
    try (final TransactionResource db = Entities.transactionFor(AlarmEntity.class)) {
        boolean first = true;
        String token = nextToken;
        while (token != null || first) {
            first = false;/*from   w  w w . j a va  2 s . c  om*/
            final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmEntity.class);
            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();
    }
    return results;
}

From source file:com.eucalyptus.cloudwatch.common.internal.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 InvalidTokenException {
    final List<AlarmHistory> results = Lists.newArrayList();
    try (final TransactionResource db = Entities.transactionFor(AlarmHistory.class)) {
        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;//from  w  w w . j a  v  a 2 s . c  o m
            final Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(token, AlarmHistory.class);
            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();
    }
    return results;
}

From source file:com.eucalyptus.cloudwatch.common.internal.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//from ww w  .  ja  va2 s .  co m
 * @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 InvalidTokenException {
    if (dimensionMap != null && dimensionMap.size() > ListMetric.MAX_DIM_NUM) {
        throw new IllegalArgumentException("Too many dimensions " + dimensionMap.size());
    }
    try (final TransactionResource db = Entities.transactionFor(ListMetric.class)) {
        Date nextTokenCreatedTime = NextTokenUtils.getNextTokenCreatedTime(nextToken, ListMetric.class);
        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;
    }
}

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

License:Open Source License

public static List<Collection<MetricStatistics>> getManyMetricStatistics(
        List<GetMetricStatisticsParams> getMetricStatisticsParamses) {
    if (getMetricStatisticsParamses == null)
        throw new IllegalArgumentException("getMetricStatisticsParamses can not be null");
    Date now = new Date();
    Map<GetMetricStatisticsParams, Collection<MetricStatistics>> resultMap = Maps.newHashMap();
    Multimap<Class, GetMetricStatisticsParams> hashGroupMap = LinkedListMultimap.create();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (getMetricStatisticsParams == null)
            throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
        getMetricStatisticsParams.validate(now);
        Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
                getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
        hashGroupMap.put(metricEntityClass, getMetricStatisticsParams);
    }/*from   w w  w . j a  v  a  2  s . c o  m*/
    for (Class metricEntityClass : hashGroupMap.keySet()) {
        try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
            // set some global criteria to start (for narrowing?)
            Date minDate = null;
            Date maxDate = null;
            Junction disjunction = Restrictions.disjunction();
            Map<GetMetricStatisticsParams, TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>> multiAggregationMap = Maps
                    .newHashMap();
            for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap.get(metricEntityClass)) {
                multiAggregationMap.put(getMetricStatisticsParams,
                        new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
                                GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE));
                Junction conjunction = Restrictions.conjunction();
                conjunction = conjunction
                        .add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
                conjunction = conjunction
                        .add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
                conjunction = conjunction
                        .add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
                conjunction = conjunction
                        .add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
                conjunction = conjunction
                        .add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
                conjunction = conjunction.add(
                        Restrictions.eq("dimensionHash", hash(getMetricStatisticsParams.getDimensionMap())));
                if (getMetricStatisticsParams.getUnits() != null) {
                    conjunction = conjunction
                            .add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
                }
                disjunction = disjunction.add(conjunction);
                if (minDate == null || getMetricStatisticsParams.getStartTime().before(minDate)) {
                    minDate = getMetricStatisticsParams.getStartTime();
                }
                if (maxDate == null || getMetricStatisticsParams.getEndTime().after(maxDate)) {
                    maxDate = getMetricStatisticsParams.getEndTime();
                }
            }
            Criteria criteria = Entities.createCriteria(metricEntityClass);
            criteria = criteria.add(Restrictions.lt("timestamp", maxDate));
            criteria = criteria.add(Restrictions.ge("timestamp", minDate));
            criteria = criteria.add(disjunction);

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.max("sampleMax"));
            projectionList.add(Projections.min("sampleMin"));
            projectionList.add(Projections.sum("sampleSize"));
            projectionList.add(Projections.sum("sampleSum"));
            projectionList.add(Projections.groupProperty("units"));
            projectionList.add(Projections.groupProperty("timestamp"));
            projectionList.add(Projections.groupProperty("accountId"));
            projectionList.add(Projections.groupProperty("metricName"));
            projectionList.add(Projections.groupProperty("metricType"));
            projectionList.add(Projections.groupProperty("namespace"));
            projectionList.add(Projections.groupProperty("dimensionHash"));
            criteria.setProjection(projectionList);
            criteria.addOrder(Order.asc("timestamp"));

            ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
            while (results.next()) {
                MetricEntity me = getMetricEntity(results);
                for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap
                        .get(metricEntityClass)) {
                    if (metricDataMatches(getMetricStatisticsParams, me)) {
                        Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = multiAggregationMap
                                .get(getMetricStatisticsParams);
                        GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensionHash());
                        MetricStatistics item = new MetricStatistics(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensions());
                        if (!aggregationMap.containsKey(key)) {
                            aggregationMap.put(key, item);
                        } else {
                            MetricStatistics totalSoFar = aggregationMap.get(key);
                            totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                            totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                            totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                            totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
                        }
                    }
                }
            }
            for (GetMetricStatisticsParams getMetricStatisticsParams : multiAggregationMap.keySet()) {
                resultMap.put(getMetricStatisticsParams,
                        multiAggregationMap.get(getMetricStatisticsParams).values());
            }
        }
    }
    List<Collection<MetricStatistics>> resultList = Lists.newArrayList();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (resultMap.get(getMetricStatisticsParams) == null) {
            resultList.add(new ArrayList<MetricStatistics>());
        } else {
            resultList.add(resultMap.get(getMetricStatisticsParams));
        }
    }
    return resultList;
}