List of usage examples for org.hibernate.criterion Restrictions disjunction
public static Disjunction disjunction()
From source file:org.apache.ode.daohib.bpel.CriteriaBuilder.java
License:Apache License
/** * Build a Hibernate {@link Criteria} from an instance filter. * @param crit target (destination) criteria * @param filter filter//w ww . j a v a2s . c om */ void buildCriteria(Criteria crit, InstanceFilter filter) { Criteria processCrit = crit.createCriteria("process"); // Filtering on PID List<String> pids = filter.getPidFilter(); if (pids != null && pids.size() > 0) { Disjunction disj = Restrictions.disjunction(); for (String pid : pids) { if (!filter.arePidsNegative()) { disj.add(Restrictions.eq("processId", pid)); } else { disj.add(Restrictions.ne("processId", pid)); } } processCrit.add(disj); } List<String> iids = filter.getIidFilter(); if (iids != null && iids.size() > 0) { Disjunction disj = Restrictions.disjunction(); for (String iid : iids) { disj.add(Restrictions.eq("id", new Long(iid))); } crit.add(disj); } // Filtering on name and namespace if (filter.getNameFilter() != null) { processCrit.add(Restrictions.like("typeName", filter.getNameFilter().replaceAll("\\*", "%"))); } if (filter.getNamespaceFilter() != null) { processCrit.add(Restrictions.like("typeNamespace", filter.getNamespaceFilter().replaceAll("\\*", "%"))); } // Specific filter for status (using a disjunction between possible statuses) if (filter.getStatusFilter() != null) { List<Short> statuses = filter.convertFilterState(); Disjunction disj = Restrictions.disjunction(); for (short status : statuses) { disj.add(Restrictions.eq("state", status)); } crit.add(disj); } // Specific filter for started and last active dates. if (filter.getStartedDateFilter() != null) { for (String sdf : filter.getStartedDateFilter()) { addFilterOnPrefixedDate(crit, sdf, "created"); } } if (filter.getLastActiveDateFilter() != null) { for (String ladf : filter.getLastActiveDateFilter()) { addFilterOnPrefixedDate(crit, ladf, "lastActiveTime"); } } // Specific filter for correlation properties if (filter.getPropertyValuesFilter() != null) { Criteria propCrit = crit.createCriteria("correlationSets").createCriteria("properties"); for (Map.Entry<String, String> corValue : filter.getPropertyValuesFilter().entrySet()) { String propName = (String) corValue.getKey(); if (propName.startsWith("{")) { String namespace = propName.substring(1, propName.lastIndexOf("}")); propName = propName.substring(propName.lastIndexOf("}") + 1, propName.length()); propCrit.add(Restrictions.eq("name", propName)).add(Restrictions.eq("namespace", namespace)) .add(Restrictions.eq("value", corValue.getValue())); } else { propCrit.add(Restrictions.eq("name", corValue.getKey())) .add(Restrictions.eq("value", corValue.getValue())); } } } // Ordering if (filter.orders != null) { for (String key : filter.orders) { boolean ascending = true; String orderKey = key; if (key.startsWith("+") || key.startsWith("-")) { orderKey = key.substring(1, key.length()); if (key.startsWith("-")) ascending = false; } if ("name".equals(orderKey)) { if (ascending) processCrit.addOrder(Property.forName("typeName").asc()); else processCrit.addOrder(Property.forName("typeName").desc()); } else if ("namespace".equals(orderKey)) { if (ascending) processCrit.addOrder(Property.forName("typeNamespace").asc()); else processCrit.addOrder(Property.forName("typeNamespace").desc()); } else if ("pid".equals(orderKey)) { if (ascending) processCrit.addOrder(Property.forName("processId").asc()); else processCrit.addOrder(Property.forName("processId").desc()); } else if ("version".equals(orderKey)) { if (ascending) processCrit.addOrder(Property.forName("version").asc()); else processCrit.addOrder(Property.forName("version").desc()); } else if ("status".equals(orderKey)) { if (ascending) crit.addOrder(Property.forName("state").asc()); else crit.addOrder(Property.forName("state").desc()); } else if ("started".equals(orderKey)) { if (ascending) crit.addOrder(Property.forName("created").asc()); else crit.addOrder(Property.forName("created").desc()); } else if ("last-active".equals(orderKey)) { if (ascending) crit.addOrder(Property.forName("lastActiveTime").asc()); else crit.addOrder(Property.forName("lastActiveTime").desc()); } } } if (filter.getLimit() > 0) crit.setMaxResults(filter.getLimit()); }
From source file:org.apache.ode.daohib.bpel.ql.HibernateInstancesQueryCompiler.java
License:Apache License
protected DisjunctionEvaluator<Criterion, Object> compileDisjunction(Collection<CommandEvaluator> childs) { return new AbstractDisjunction<Criterion, Object>(childs) { public Criterion evaluate(Object arg) { Disjunction conj = Restrictions.disjunction(); for (CommandEvaluator eval : childs) { conj.add((Criterion) eval.evaluate(null)); }/*from w w w . j a v a 2 s . c o m*/ return conj; }; }; }
From source file:org.apache.ode.daohib.bpel.ql.HibernateInstancesQueryCompiler.java
License:Apache License
protected EqualityEvaluator<String, Criterion, Object> compileEqual(final Equality eq) { if (eq.getIdentifier() instanceof Property) { propertyInQuery = true;//from w w w. ja v a 2 s .c o m final Property property = (Property) eq.getIdentifier(); return new EqualityEvaluator<String, Criterion, Object>() { public Criterion evaluate(Object paramValue) { Conjunction conj = Restrictions.conjunction(); if (!StringUtils.isEmpty(property.getNamespace())) { conj.add(Restrictions.eq(PROPERTY_NS_DB_FIELD, property.getNamespace())); } conj.add(Restrictions.eq(PROPERTY_NAME_DB_FIELD, property.getName())); conj.add(Restrictions.eq(PROPERTY_VALUE_DB_FIELD, eq.getValue().getValue())); return conj; }; public String getIdentifier() { return property.toString(); }; }; } else { final String fieldName = eq.getIdentifier().getName(); final Object value = eq.getValue().getValue(); final String dbField = getDBField(fieldName); if (INSTANCE_STATUS_FIELD.equals(fieldName)) { return new FieldValueEquality(INSTANCE_STATUS_FIELD) { /** * @see org.apache.ode.ql.eval.skel.CommandEvaluator#evaluate(java.lang.Object) */ public Criterion evaluate(Object paramValue) { short noState = 200; // TODO move to constants Disjunction disj = Restrictions.disjunction(); if (STATUS_ACTIVE.equals(paramValue)) { disj.add(Restrictions.eq(dbField, ProcessState.STATE_NEW)); disj.add(Restrictions.eq(dbField, ProcessState.STATE_ACTIVE)); disj.add(Restrictions.eq(dbField, ProcessState.STATE_READY)); } else if (STATUS_SUSPENDED.equals(paramValue)) { disj.add(Restrictions.eq(dbField, ProcessState.STATE_SUSPENDED)); } else if (STATUS_ERROR.equals(value)) { disj.add(Restrictions.eq(dbField, noState)); // Error instance state doesn't exist yet } else if (STATUS_COMPLETED.equals(paramValue)) { disj.add(Restrictions.eq(dbField, ProcessState.STATE_COMPLETED_OK)); } else if (STATUS_TERMINATED.equals(paramValue)) { disj.add(Restrictions.eq(dbField, ProcessState.STATE_TERMINATED)); } else if (STATUS_FAULTED.equals(paramValue)) { disj.add(Restrictions.eq(dbField, ProcessState.STATE_COMPLETED_WITH_FAULT)); } else { disj.add(Restrictions.eq(dbField, noState)); // Non existent state } return disj; } }; } return new DBFieldValueEq(dbField, value); } }
From source file:org.apache.ode.daohib.bpel.ql.HibernateInstancesQueryCompiler.java
License:Apache License
protected INEvaluator<String, Criterion, Object> compileIn(final In in) { if (in.getIdentifier() instanceof Property) { propertyInQuery = true;//ww w . j a v a 2 s. c o m final Property property = (Property) in.getIdentifier(); return new INEvaluator<String, Criterion, Object>() { public Criterion evaluate(Object paramValue) { Disjunction disj = Restrictions.disjunction(); String propertyNS = property.getNamespace(); String propertyName = property.getName(); for (Value value : in.getValues()) { Conjunction conj = Restrictions.conjunction(); if (!StringUtils.isEmpty(property.getNamespace())) { conj.add(Restrictions.gt(PROPERTY_NS_DB_FIELD, propertyNS)); } conj.add(Restrictions.gt(PROPERTY_NAME_DB_FIELD, propertyName)); conj.add(Restrictions.gt(PROPERTY_VALUE_DB_FIELD, value.getValue())); disj.add(conj); } return disj; }; public String getIdentifier() { return property.toString(); }; }; } else { final String fieldName = in.getIdentifier().getName(); if (INSTANCE_STATUS_FIELD.equals(fieldName)) { short noState = 200; // TODO move to constants final Disjunction disj = Restrictions.disjunction(); final Collection values = ValuesHelper.extract((Collection<Value>) in.getValues()); if (values.contains(STATUS_ACTIVE)) { disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_NEW)); disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_ACTIVE)); disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_READY)); } if (values.contains(STATUS_SUSPENDED)) { disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_SUSPENDED)); } if (values.contains(STATUS_ERROR)) { disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, noState)); // Error instance state doesn't exist yet } if (values.contains(STATUS_COMPLETED)) { disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_COMPLETED_OK)); } if (values.contains(STATUS_TERMINATED)) { disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_TERMINATED)); } if (values.contains(STATUS_FAULTED)) { disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_COMPLETED_WITH_FAULT)); } return new INEvaluator<String, Criterion, Object>() { public Criterion evaluate(Object paramValue) { return disj; }; public String getIdentifier() { return INSTANCE_STATUS_DB_FIELD; }; }; } else { final Collection objValues; final Collection<Value> values = in.getValues(); if (INSTANCE_ID_FIELD.equals(fieldName)) { objValues = new ArrayList<Long>(values.size()); for (Value value : values) { objValues.add(Long.valueOf((String) value.getValue())); } } else if (INSTANCE_STARTED_FIELD.equals(fieldName) || INSTANCE_LAST_ACTIVE_FIELD.equals(fieldName)) { objValues = new ArrayList<Date>(values.size()); try { for (Value value : values) { objValues.add(ISO8601DateParser.parse((String) value.getValue())); } } catch (ParseException ex) { // TODO throw new RuntimeException(ex); } } else { objValues = ValuesHelper.extract((Collection<Value>) values); } final String dbField = getDBField(fieldName); return new INEvaluator<String, Criterion, Object>() { /** * @see org.apache.ode.ql.eval.skel.CommandEvaluator#evaluate(java.lang.Object) */ public Criterion evaluate(Object paramValue) { return Restrictions.in(dbField, objValues); } /** * @see org.apache.ode.ql.eval.skel.Identified#getIdentifier() */ public String getIdentifier() { return dbField; } }; } } }
From source file:org.brushingbits.jnap.persistence.hibernate.DynaQueryBuilder.java
License:Apache License
public Criteria build() throws QueryException { Matcher matcher = DYNA_QUERY_PATTERN.matcher(this.dynaQuery); if (!matcher.matches()) { throw new QueryException("The DynaQuery syntax is incorrect. It must start with 'findBy' " + ", findUniqueBy or 'countBy' expression followed by property expressions and operators.", this.dynaQuery); }//from w ww.j a va 2 s . c o m Criteria criteria = this.createCriteria(matcher.group(1).equals("countBy")); String dynaQueryExpression = matcher.group(2); // order by Matcher orderByMatcher = ORDER_BY_PATTERN.matcher(dynaQueryExpression); if (orderByMatcher.find()) { dynaQueryExpression = StringUtils.remove(dynaQueryExpression, orderByMatcher.group()); String orderByProperty = normalizePropertyName(orderByMatcher.group(3)); String orderByDirection = orderByMatcher.group(4); Order orderBy = "Desc".equals(orderByDirection) ? Order.desc(orderByProperty) : Order.asc(orderByProperty); criteria.addOrder(orderBy); } // split properties String[] properties = DYNA_QUERY_OPERATOR_PATTERN.split(dynaQueryExpression); if (properties.length == 0 || properties.length > 2) { throw new QueryException(format( "The DynaQuery syntax is incorrect. Dynamic queries must have " + "at least one property an no more than two (yours has {0}).\nYou can use one of " + "the following logical operators ({1}) and these expression operators ({2})", properties.length, LOGICAL_OPERATOR_AND + ", " + LOGICAL_OPERATOR_OR, StringUtils.join(EXPRESSION_OPERATORS, ", ")), this.dynaQuery); } Matcher logicalOperatorsMatcher = DYNA_QUERY_OPERATOR_PATTERN.matcher(dynaQueryExpression); String logicalOperator = logicalOperatorsMatcher.find() ? logicalOperatorsMatcher.group(1) : LOGICAL_OPERATOR_AND; Junction junction = LOGICAL_OPERATOR_OR.equals(logicalOperator) ? Restrictions.disjunction() : Restrictions.conjunction(); for (String property : properties) { junction.add(this.createCriterion(property)); } criteria.add(junction); return criteria; }
From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java
License:Open Source License
/** * Retrieves an iterator over the compliance snapshots for the specified consumer. * * @param consumerUUID/*from ww w. j a v a2s . c om*/ * The UUID for the consumer for which to retrieve compliance snapshots. * * @param startDate * The start date to use to filter snapshots retrieved. If specified, only snapshots occurring * after the start date, and the snapshot immediately preceding it, will be retrieved. * * @param endDate * The end date to use to filter snapshots retrieved. If specified, only snapshots occurring * before the end date will be retrieved. * * @param pageRequest * A PageRequest instance containing paging information from the request. If null, no paging * will be performed. * * @return * A Page instance containing an iterator over the snapshots for the specified consumer, and * the paging information for the query. */ @SuppressWarnings("checkstyle:indentation") public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate, Date endDate, PageRequest pageRequest) { Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>(); page.setPageRequest(pageRequest); Session session = this.currentSession(); Criteria query = session.createCriteria(Compliance.class, "comp1"); query.createAlias("comp1.consumer", "cons1"); query.add(Restrictions.eq("cons1.uuid", consumerUUID)); if (startDate != null) { DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2"); subquery.createAlias("comp2.consumer", "cons2"); subquery.createAlias("cons2.consumerState", "state2"); subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"), Restrictions.gt("state2.deleted", startDate))); subquery.add(Restrictions.lt("state2.created", startDate)); subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid")); subquery.add(Restrictions.lt("comp2.date", startDate)); subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date"))); query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate)) .add(Subqueries.propertyEq("comp1.date", subquery))); } if (endDate != null) { query.add(Restrictions.le("comp1.date", endDate)); } query.setCacheMode(CacheMode.IGNORE); query.setReadOnly(true); if (pageRequest != null && pageRequest.isPaging()) { page.setMaxRecords(this.getRowCount(query)); query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage()); query.setMaxResults(pageRequest.getPerPage()); if (pageRequest.getSortBy() != null) { query.addOrder( pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy()) : Order.desc(pageRequest.getSortBy())); } } page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session, query.scroll(ScrollMode.FORWARD_ONLY), 0)); return page; }
From source file:org.candlepin.model.ConsumerCurator.java
License:Open Source License
/** * Get host consumer for a guest system id. * * As multiple hosts could have reported the same guest ID, we find the newest * and assume this is the authoritative host for the guest. * * This search needs to be case insensitive as some hypervisors report uppercase * guest UUIDs, when the guest itself will report lowercase. * * @param guestId a virtual guest ID (not a consumer UUID) * @return host consumer who most recently reported the given guestId (if any) */// w w w .j av a 2 s . co m @Transactional public Consumer getHost(String guestId, Owner owner) { Disjunction guestIdCrit = Restrictions.disjunction(); for (String possibleId : Util.getPossibleUuids(guestId)) { guestIdCrit.add(Restrictions.eq("guestId", possibleId).ignoreCase()); } Criteria crit = currentSession().createCriteria(GuestId.class).createAlias("consumer", "gconsumer") .add(Restrictions.eq("gconsumer.owner", owner)).addOrder(Order.desc("updated")).setMaxResults(1) .setProjection(Projections.property("consumer")); return (Consumer) crit.add(guestIdCrit).uniqueResult(); }
From source file:org.candlepin.model.FactFilterBuilder.java
License:Open Source License
@Override protected Criterion buildCriteriaForKey(String key, List<String> values) { Disjunction valuesCriteria = Restrictions.disjunction(); for (String value : values) { if (StringUtils.isEmpty(value)) { valuesCriteria.add(Restrictions.isNull("cfacts.elements")); valuesCriteria.add(Restrictions.eq("cfacts.elements", "")); } else {/* www. jav a 2s . c o m*/ valuesCriteria.add(new FactLikeExpression("cfacts.elements", value, true)); } } DetachedCriteria dc = DetachedCriteria.forClass(Consumer.class, "subcons") .add(Restrictions.eqProperty("this.id", "subcons.id")).createAlias("subcons.facts", "cfacts") // Match the key, case sensitive .add(new FactLikeExpression("cfacts.indices", key, false)) // Match values, case insensitive .add(valuesCriteria).setProjection(Projections.property("subcons.id")); return Subqueries.exists(dc); }
From source file:org.candlepin.model.PoolCurator.java
License:Open Source License
/** * Lists all pools that either belong to owner, or match a subscription id in subIds * * @param owner owner/* w w w . ja v a2 s. c o m*/ * @param subIds subscription ids * @return resulting list of pools */ @SuppressWarnings("unchecked") public List<Pool> getPoolsForOwnerRefresh(Owner owner, List<String> subIds) { Criteria crit = currentSession().createCriteria(Pool.class); Disjunction ownerOrIds = Restrictions.disjunction(); if (!subIds.isEmpty()) { crit.createAlias("sourceSubscription", "sourceSub", JoinType.LEFT_OUTER_JOIN); ownerOrIds.add(Restrictions.in("sourceSub.subscriptionId", subIds)); } ownerOrIds.add(Restrictions.eq("owner", owner)); crit.add(ownerOrIds); // Add order to help avoid deadlocks when refreshing pools crit.addOrder(Order.asc("id")); return crit.list(); }
From source file:org.cast.isi.data.builder.ISIResponseCriteriaBuilder.java
License:Open Source License
@Override public void buildUnordered(Criteria criteria) { // only get responses related to specific site(s) if (siteListModel != null && !siteListModel.getObject().isEmpty()) { criteria.createAlias("user", "user").createAlias("user.periods", "period", JoinType.LEFT_OUTER_JOIN); List<Site> siteList = siteListModel.getObject(); Disjunction siteRestriction = Restrictions.disjunction(); siteRestriction.add(Restrictions.in("period.site", siteList)); criteria.add(siteRestriction);/*from w ww .j a v a2 s . c o m*/ criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // Remove duplicate rows as a result of the INNER JOIN } super.buildUnordered(criteria); // may want to push this to cwm - no cache used for large report data, more than 1000 objects criteria.setCacheable(canCache); }