List of usage examples for org.hibernate.criterion Restrictions conjunction
public static Conjunction conjunction()
From source file:com.eucalyptus.autoscaling.service.AutoScalingService.java
License:Open Source License
public DescribeTagsResponseType describeTags(final DescribeTagsType request) throws EucalyptusCloudException { final DescribeTagsResponseType reply = request.getReply(); //TODO: MaxRecords / NextToken support for DescribeTags final Collection<Predicate<Tag>> tagFilters = Lists.newArrayList(); for (final Filter filter : request.filters()) { final Function<Tag, String> extractor = tagFilterExtractors.get(filter.getName()); if (extractor == null) { throw new AutoScalingClientException("ValidationError", "Filter type " + filter.getName() + " is not correct. Allowed Filter types are: auto-scaling-group key value propagate-at-launch"); }//from w w w . j av a 2 s. c o m final Function<String, String> tagValueConverter = MoreObjects .firstNonNull(tagValuePreProcessors.get(filter.getName()), Functions.identity()); tagFilters.add(Predicates .compose(Predicates.in(Collections2.transform(filter.values(), tagValueConverter)), extractor)); } final Context context = Contexts.lookup(); final Ordering<Tag> ordering = Ordering.natural().onResultOf(Tags.resourceId()) .compound(Ordering.natural().onResultOf(Tags.key())) .compound(Ordering.natural().onResultOf(Tags.value())); try { final TagDescriptionList tagDescriptions = new TagDescriptionList(); for (final Tag tag : ordering.sortedCopy(Tags.list(context.getUserFullName().asAccountFullName(), Predicates.and(tagFilters), Restrictions.conjunction(), Collections.emptyMap()))) { if (Permissions.isAuthorized(AutoScalingPolicySpec.VENDOR_AUTOSCALING, tag.getResourceType(), tag.getKey(), context.getAccount(), PolicySpec.describeAction(AutoScalingPolicySpec.VENDOR_AUTOSCALING, tag.getResourceType()), context.getAuthContext())) { tagDescriptions.getMember().add(TypeMappers.transform(tag, TagDescription.class)); } } if (!tagDescriptions.getMember().isEmpty()) { reply.getDescribeTagsResult().setTags(tagDescriptions); } } catch (AutoScalingMetadataNotFoundException e) { handleException(e); } return reply; }
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);/* w ww.j a va 2s . c o m*/ 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<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;/* ww w .j a v a 2s. 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// w ww . j av a 2s. 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. ja 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; }
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) {// w w w. j a v a 2 s . com 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 . j a va 2 s . c om 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<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 va 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//ww w. j ava2s. 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.cluster.callback.VmStateCallback.java
License:Open Source License
private static Supplier<Set<String>> createInstanceSupplier(final StateUpdateMessageCallback<Cluster, ?, ?> cb, final Predicate<VmInstance> filter) { return Suppliers.memoize(new Supplier<Set<String>>() { @Override//from w w w . ja va 2 s. c o m public Set<String> get() { final EntityTransaction db = Entities.get(VmInstance.class); try { Collection<VmInstance> clusterInstances = VmInstances.list(null, Restrictions.conjunction(), Collections.<String, String>emptyMap(), filter); Collection<String> instanceNames = Collections2.transform(clusterInstances, CloudMetadatas.toDisplayName()); return Sets.newHashSet(instanceNames); } catch (Exception ex) { Logs.extreme().error(ex, ex); return Sets.newHashSet(); } finally { db.rollback(); } } }); }