Example usage for org.hibernate.criterion Restrictions ge

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

Introduction

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

Prototype

public static SimpleExpression ge(String propertyName, Object value) 

Source Link

Document

Apply a "greater than or equal" constraint to the named property

Usage

From source file:com.eharmony.matching.seeking.translator.hibernate.HibernateQueryTranslator.java

License:Apache License

@Override
public Criterion gte(String fieldName, Object value) {
    return Restrictions.ge(fieldName, value);
}

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

License:Apache License

public Criterion build(String propertyName, Object value) {

    return Restrictions.ge(propertyName, value);
}

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  .ja  va  2  s. co  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// w ww.  j  a v  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 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 . ja va 2s.  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;
}

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

License:Open Source License

public static Collection<MetricStatistics> getMetricStatistics(
        GetMetricStatisticsParams getMetricStatisticsParams) {
    if (getMetricStatisticsParams == null)
        throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
    Date now = new Date();
    getMetricStatisticsParams.validate(now);
    Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
            getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
    Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
            GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE);
    try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
        Criteria criteria = Entities.createCriteria(metricEntityClass);
        criteria = criteria.add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
        criteria = criteria.add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
        criteria = criteria.add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
        criteria = criteria.add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
        criteria = criteria.add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
        criteria = criteria.add(Restrictions.eq("dimensionHash", getMetricStatisticsParams.getDimensionHash()));
        if (getMetricStatisticsParams.getUnits() != null) {
            criteria = criteria.add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
        }//from   w w w. j  a v  a2 s  .  c o  m

        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"));
        criteria.setProjection(projectionList);
        criteria.addOrder(Order.asc("timestamp"));
        ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
        while (results.next()) {
            MetricEntity me = getMetricEntity(getMetricStatisticsParams.getAccountId(),
                    getMetricStatisticsParams.getMetricName(), getMetricStatisticsParams.getNamespace(),
                    getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash(),
                    results);
            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());
            }
        }
    }
    return Lists.newArrayList(aggregationMap.values());
}

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  .j a v a 2s . c  o m*/
        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//from w w w  .  ja  v a 2  s  .c o 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 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.cloudwatch.domain.metricdata.MetricManager.java

License:Open Source License

public static Collection<MetricStatistics> getMetricStatistics(String accountId, String metricName,
        String namespace, Map<String, String> dimensionMap, MetricType metricType, Units units, Date startTime,
        Date endTime, Integer period) {
    if (dimensionMap == null) {
        dimensionMap = new HashMap<String, String>();
    } else if (dimensionMap.size() > MetricEntity.MAX_DIM_NUM) {
        throw new IllegalArgumentException("Too many dimensions for metric, " + dimensionMap.size());
    }/*from w w w.  j a  v  a  2 s  .c o  m*/
    TreeSet<DimensionEntity> dimensions = new TreeSet<DimensionEntity>();
    for (Map.Entry<String, String> entry : dimensionMap.entrySet()) {
        DimensionEntity d = new DimensionEntity();
        d.setName(entry.getKey());
        d.setValue(entry.getValue());
        dimensions.add(d);
    }
    Date now = new Date();
    if (endTime == null)
        endTime = now;
    if (startTime == null)
        startTime = new Date(now.getTime() - 60 * 60 * 1000L);
    startTime = stripSeconds(startTime);
    endTime = stripSeconds(endTime);
    if (startTime.after(endTime)) {
        throw new IllegalArgumentException("Start time must be after end time");
    }
    if (period == null) {
        period = 60;
    }
    if (period % 60 != 0) {
        throw new IllegalArgumentException("Period must be a multiple of 60");
    }
    if (period < 0) {
        throw new IllegalArgumentException("Period must be greater than 0");
    }
    if (period == 0) {
        throw new IllegalArgumentException("Period must not equal 0");
    }
    if (metricType == null) {
        throw new IllegalArgumentException("metricType must not be null");
    }
    if (accountId == null) {
        throw new IllegalArgumentException("accountId must not be null");
    }
    if (metricName == null) {
        throw new IllegalArgumentException("metricName must not be null");
    }
    if (namespace == null) {
        throw new IllegalArgumentException("namespace must not be null");
    }
    String hash = hash(dimensions);
    Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(metricType, hash);
    Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
            GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE);
    EntityTransaction db = Entities.get(metricEntityClass);
    try {
        Criteria criteria = Entities.createCriteria(metricEntityClass);
        criteria = criteria.add(Restrictions.eq("accountId", accountId));
        criteria = criteria.add(Restrictions.eq("metricName", metricName));
        criteria = criteria.add(Restrictions.eq("namespace", namespace));
        criteria = criteria.add(Restrictions.lt("timestamp", endTime));
        criteria = criteria.add(Restrictions.ge("timestamp", startTime));
        criteria = criteria.add(Restrictions.eq("dimensionHash", hash));
        if (units != null) {
            criteria = criteria.add(Restrictions.eq("units", units));
        }
        criteria = criteria.addOrder(Order.asc("creationTimestamp"));
        criteria = criteria.addOrder(Order.asc("naturalId"));
        Collection results = criteria.list();
        for (Object o : results) {
            MetricEntity me = (MetricEntity) o;
            // Note: dimensions from metric entity are the actual dimensions for the point.  dimensions passed in are from the
            // hash (used for aggregation).  The hash dimensions are what we want.
            GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me, startTime, period,
                    hash);
            MetricStatistics item = new MetricStatistics(me, startTime, period, dimensions);
            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());
            }
        }
        db.commit();
    } catch (RuntimeException ex) {
        Logs.extreme().error(ex, ex);
        throw ex;
    } finally {
        if (db.isActive())
            db.rollback();
    }
    return Lists.newArrayList(aggregationMap.values());
}

From source file:com.eucalyptus.reporting.art.generator.AbstractArtGenerator.java

License:Open Source License

protected Criterion between(final Long beginInclusive, final Long endExclusive) {
    return Restrictions.conjunction().add(Restrictions.ge(TIMESTAMP_MS, beginInclusive))
            .add(before(endExclusive));/* w  w w  .  j  a va 2  s  .c om*/
}