List of usage examples for javax.persistence.criteria CriteriaBuilder and
Predicate and(Predicate... restrictions);
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateNumber(String theParamName, List<? extends IQueryParameterType> theList) { if (Boolean.TRUE.equals(theList.get(0).getMissing())) { addPredicateParamMissing("myParamsNumber", theParamName, ResourceIndexedSearchParamNumber.class); return;//from w w w . ja va 2 s . com } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceIndexedSearchParamNumber> from = cq.from(ResourceIndexedSearchParamNumber.class); cq.select(from.get("myResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) { continue; } if (params instanceof NumberParam) { NumberParam param = (NumberParam) params; BigDecimal value = param.getValue(); if (value == null) { continue; } final Expression<BigDecimal> fromObj = from.get("myValue"); ParamPrefixEnum prefix = ObjectUtils.defaultIfNull(param.getPrefix(), ParamPrefixEnum.EQUAL); String invalidMessageName = "invalidNumberPrefix"; String valueAsString = param.getValue().toPlainString(); Predicate num = createPredicateNumeric(builder, params, prefix, value, fromObj, invalidMessageName, valueAsString); codePredicates.add(num); } else { throw new IllegalArgumentException("Invalid token type: " + params.getClass()); } } List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(builder.equal(from.get("myResourceType"), myResourceName)); predicates.add(builder.equal(from.get("myParamName"), theParamName)); predicates.add(builder.or(toArray(codePredicates))); createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class)); createPredicateLastUpdatedForIndexedSearchParam(builder, from, predicates); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); doSetPids(q.getResultList()); }
From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA/*from ww w .j a v a2 s .c o m*/ * @param filters * @param entityClazz * @param isDistinct trueSQLdistinctfalse? * @return */ public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) { return new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (orderParams != null && orderParams.size() > 0) { /* CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class); Root<Foo> from = criteriaQuery.from(Foo.class); CriteriaQuery<Foo> select = criteriaQuery.select(from); criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name"))); */ List<Order> orders = new ArrayList<Order>(orderParams.size()); for (OrderParam orderParam : orderParams) { if (orderParam != null && orderParam.getField() != null) { String fields[] = StringUtil.split(orderParam.getField(), '.'); Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]); for (int i = 1, len = fields.length; i < len; ++i) { expression = expression.get(fields[i]); } if (expression != null) { Order order = (orderParam.getType() == null || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression) : builder.desc(expression); orders.add(order); // query.orderBy(order); } } } query.orderBy(orders); } query.distinct(isDistinct); if (Collections3.isNotEmpty(filters)) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, '.'); Path expression = null; ////// ? boolean hasJoin = names[0].startsWith("[join]"); String fn = hasJoin ? names[0].substring(6) : names[0]; boolean isNotDateType = !(filter.value instanceof Date); try { expression = hasJoin ? root.join(fn) : root.get(fn); if (isNotDateType && isDateType(expression.getJavaType())) { // filter.value?? filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); continue; // ?? } boolean isPropertyNotValid = false; for (int i = 1; i < names.length; i++) { try { expression = expression.get(names[i]); if (isNotDateType && isDateType(expression.getJavaType())) { filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); isPropertyNotValid = true; // break; // ?? } } if (expression == null || isPropertyNotValid) { continue; } /////// // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.or(like)); } break; case ANDLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case ANDNOTLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notLike(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case OREQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.equal(expression, values[i]); } predicates.add(builder.or(like)); } break; case ANDNOTEQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notEqual(expression, values[i]); } predicates.add(builder.and(like)); } break; case NOTEQ: predicates.add(builder.notEqual(expression, (Comparable) filter.value)); break; case NOTLIKE: predicates.add(builder.notLike(expression, "%" + filter.value + "%")); break; case NULL: predicates.add(builder.isNull(expression)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; // case IN: // predicates.add(builder.in(expression).in(values)); // break; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateUri(String theParamName, List<? extends IQueryParameterType> theList) { if (Boolean.TRUE.equals(theList.get(0).getMissing())) { addPredicateParamMissing("myParamsUri", theParamName, ResourceIndexedSearchParamUri.class); return;/* ww w . ja v a 2s . c om*/ } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceIndexedSearchParamUri> from = cq.from(ResourceIndexedSearchParamUri.class); cq.select(from.get("myResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) { continue; } if (params instanceof UriParam) { UriParam param = (UriParam) params; String value = param.getValue(); if (value == null) { continue; } Path<Object> fromObj = from.get("myUri"); Predicate predicate; if (param.getQualifier() == UriParamQualifierEnum.ABOVE) { /* * :above is an inefficient query- It means that the user is supplying a more specific URL (say * http://example.com/foo/bar/baz) and that we should match on any URLs that are less * specific but otherwise the same. For example http://example.com and http://example.com/foo would both * match. * * We do this by querying the DB for all candidate URIs and then manually checking each one. This isn't * very efficient, but this is also probably not a very common type of query to do. * * If we ever need to make this more efficient, lucene could certainly be used as an optimization. */ ourLog.info("Searching for candidate URI:above parameters for Resource[{}] param[{}]", myResourceName, theParamName); Collection<String> candidates = myResourceIndexedSearchParamUriDao .findAllByResourceTypeAndParamName(myResourceName, theParamName); List<String> toFind = new ArrayList<String>(); for (String next : candidates) { if (value.length() >= next.length()) { if (value.substring(0, next.length()).equals(next)) { toFind.add(next); } } } if (toFind.isEmpty()) { continue; } predicate = fromObj.as(String.class).in(toFind); } else if (param.getQualifier() == UriParamQualifierEnum.BELOW) { predicate = builder.like(fromObj.as(String.class), createLeftMatchLikeExpression(value)); } else { predicate = builder.equal(fromObj.as(String.class), value); } codePredicates.add(predicate); } else { throw new IllegalArgumentException("Invalid URI type: " + params.getClass()); } } if (codePredicates.isEmpty()) { doSetPids(new HashSet<Long>()); return; } List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(builder.equal(from.get("myResourceType"), myResourceName)); predicates.add(builder.equal(from.get("myParamName"), theParamName)); predicates.add(builder.or(toArray(codePredicates))); createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class)); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); doSetPids(new HashSet<Long>(q.getResultList())); }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateTag(List<List<? extends IQueryParameterType>> theList, String theParamName, DateRangeParam theLastUpdated) { TagTypeEnum tagType;// w w w . j ava2 s . c o m if (Constants.PARAM_TAG.equals(theParamName)) { tagType = TagTypeEnum.TAG; } else if (Constants.PARAM_PROFILE.equals(theParamName)) { tagType = TagTypeEnum.PROFILE; } else if (Constants.PARAM_SECURITY.equals(theParamName)) { tagType = TagTypeEnum.SECURITY_LABEL; } else { throw new IllegalArgumentException("Param name: " + theParamName); // shouldn't happen } /* * CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = * builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class); * cq.select(from.get("myId").as(Long.class)); * * Subquery<Long> subQ = cq.subquery(Long.class); Root<? extends BaseResourceIndexedSearchParam> subQfrom = * subQ.from(theParamTable); subQ.select(subQfrom.get("myResourcePid").as(Long.class)); * Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName); Predicate subQtype = * builder.equal(subQfrom.get("myResourceType"), myResourceName); * subQ.where(builder.and(subQtype, subQname)); * * List<Predicate> predicates = new ArrayList<Predicate>(); * predicates.add(builder.not(builder.in(from.get("myId")).value(subQ))); * predicates.add(builder.equal(from.get("myResourceType"), * myResourceName)); predicates.add(builder.isNull(from.get("myDeleted"))); createPredicateResourceId(builder, cq, * predicates, from.get("myId").as(Long.class)); */ List<Pair<String, String>> notTags = Lists.newArrayList(); for (List<? extends IQueryParameterType> nextAndParams : theList) { for (IQueryParameterType nextOrParams : nextAndParams) { if (nextOrParams instanceof TokenParam) { TokenParam param = (TokenParam) nextOrParams; if (param.getModifier() == TokenParamModifier.NOT) { if (isNotBlank(param.getSystem()) || isNotBlank(param.getValue())) { notTags.add(Pair.of(param.getSystem(), param.getValue())); } } } } } /* * We have a parameter of ResourceType?_tag:not=foo This means match resources that don't have the given tag(s) */ if (notTags.isEmpty() == false) { // CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); // CriteriaQuery<Long> cq = builder.createQuery(Long.class); // Root<ResourceTable> from = cq.from(ResourceTable.class); // cq.select(from.get("myId").as(Long.class)); // // Subquery<Long> subQ = cq.subquery(Long.class); // Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class); // subQ.select(subQfrom.get("myResourceId").as(Long.class)); // Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName); // Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName); // subQ.where(builder.and(subQtype, subQname)); // // List<Predicate> predicates = new ArrayList<Predicate>(); // predicates.add(builder.not(builder.in(from.get("myId")).value(subQ))); // predicates.add(builder.equal(from.get("myResourceType"), myResourceName)); // predicates.add(builder.isNull(from.get("myDeleted"))); // createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class)); } for (List<? extends IQueryParameterType> nextAndParams : theList) { boolean haveTags = false; for (IQueryParameterType nextParamUncasted : nextAndParams) { if (nextParamUncasted instanceof TokenParam) { TokenParam nextParam = (TokenParam) nextParamUncasted; if (isNotBlank(nextParam.getValue())) { haveTags = true; } else if (isNotBlank(nextParam.getSystem())) { throw new InvalidRequestException("Invalid " + theParamName + " parameter (must supply a value/code and not just a system): " + nextParam.getValueAsQueryToken(myContext)); } } else { UriParam nextParam = (UriParam) nextParamUncasted; if (isNotBlank(nextParam.getValue())) { haveTags = true; } } } if (!haveTags) { continue; } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); boolean paramInverted = false; List<Pair<String, String>> tokens = Lists.newArrayList(); for (IQueryParameterType nextOrParams : nextAndParams) { String code; String system; if (nextOrParams instanceof TokenParam) { TokenParam nextParam = (TokenParam) nextOrParams; code = nextParam.getValue(); system = nextParam.getSystem(); if (nextParam.getModifier() == TokenParamModifier.NOT) { paramInverted = true; } } else { UriParam nextParam = (UriParam) nextOrParams; code = nextParam.getValue(); system = null; } if (isNotBlank(code)) { tokens.add(Pair.of(system, code)); } } if (tokens.isEmpty()) { continue; } if (paramInverted) { ourLog.debug("Searching for _tag:not"); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTable> newFrom = cq.from(ResourceTable.class); Subquery<Long> subQ = cq.subquery(Long.class); Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class); subQ.select(subQfrom.get("myResourceId").as(Long.class)); cq.select(newFrom.get("myId").as(Long.class)); List<Predicate> andPredicates = new ArrayList<Predicate>(); andPredicates = new ArrayList<Predicate>(); andPredicates.add(builder.equal(newFrom.get("myResourceType"), myResourceName)); andPredicates.add(builder.not(builder.in(newFrom.get("myId")).value(subQ))); Subquery<Long> defJoin = subQ.subquery(Long.class); Root<TagDefinition> defJoinFrom = defJoin.from(TagDefinition.class); defJoin.select(defJoinFrom.get("myId").as(Long.class)); subQ.where(subQfrom.get("myTagId").as(Long.class).in(defJoin)); List<Predicate> orPredicates = createPredicateTagList(defJoinFrom, builder, tagType, tokens); defJoin.where(toArray(orPredicates)); cq.where(toArray(andPredicates)); TypedQuery<Long> q = myEntityManager.createQuery(cq); Set<Long> pids = new HashSet<Long>(q.getResultList()); doSetPids(pids); continue; } CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTag> from = cq.from(ResourceTag.class); List<Predicate> andPredicates = new ArrayList<Predicate>(); andPredicates.add(builder.equal(from.get("myResourceType"), myResourceName)); From<ResourceTag, TagDefinition> defJoin = from.join("myTag"); Join<?, ResourceTable> defJoin2 = from.join("myResource"); Predicate notDeletedPredicatePrediate = builder.isNull(defJoin2.get("myDeleted")); andPredicates.add(notDeletedPredicatePrediate); List<Predicate> orPredicates = createPredicateTagList(defJoin, builder, tagType, tokens); andPredicates.add(builder.or(toArray(orPredicates))); if (theLastUpdated != null) { andPredicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, defJoin2)); } createPredicateResourceId(builder, cq, andPredicates, from.get("myResourceId").as(Long.class)); Predicate masterCodePredicate = builder.and(toArray(andPredicates)); cq.select(from.get("myResourceId").as(Long.class)); cq.where(masterCodePredicate); TypedQuery<Long> q = myEntityManager.createQuery(cq); Set<Long> pids = new HashSet<Long>(q.getResultList()); doSetPids(pids); } }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateReference(String theParamName, List<? extends IQueryParameterType> theList) { assert theParamName.contains(".") == false; if (Boolean.TRUE.equals(theList.get(0).getMissing())) { addPredicateParamMissingResourceLink("myResourceLinks", theParamName); return;// w w w. j a v a2s .c om } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceLink> from = cq.from(ResourceLink.class); cq.select(from.get("mySourceResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (addPredicateMissingFalseIfPresentForResourceLink(builder, theParamName, from, codePredicates, nextOr)) { continue; } if (params instanceof ReferenceParam) { ReferenceParam ref = (ReferenceParam) params; if (isBlank(ref.getChain())) { IIdType dt = new IdDt(ref.getBaseUrl(), ref.getResourceType(), ref.getIdPart(), null); if (dt.hasBaseUrl()) { if (myCallingDao.getConfig().getTreatBaseUrlsAsLocal().contains(dt.getBaseUrl())) { dt = dt.toUnqualified(); } else { ourLog.debug("Searching for resource link with target URL: {}", dt.getValue()); Predicate eq = builder.equal(from.get("myTargetResourceUrl"), dt.getValue()); codePredicates.add(eq); continue; } } List<Long> targetPid; try { targetPid = myCallingDao.translateForcedIdToPids(dt); } catch (ResourceNotFoundException e) { doSetPids(new ArrayList<Long>()); return; } for (Long next : targetPid) { ourLog.debug("Searching for resource link with target PID: {}", next); Predicate eq = builder.equal(from.get("myTargetResourcePid"), next); codePredicates.add(eq); } } else { List<Class<? extends IBaseResource>> resourceTypes; String resourceId; if (!ref.getValue().matches("[a-zA-Z]+\\/.*")) { String paramPath = myContext.getResourceDefinition(myResourceType) .getSearchParam(theParamName).getPath(); if (paramPath.endsWith(".as(Reference)")) { paramPath = paramPath.substring(0, paramPath.length() - ".as(Reference)".length()) + "Reference"; } BaseRuntimeChildDefinition def = myContext.newTerser().getDefinition(myResourceType, paramPath); if (def instanceof RuntimeChildChoiceDefinition) { RuntimeChildChoiceDefinition choiceDef = (RuntimeChildChoiceDefinition) def; resourceTypes = choiceDef.getResourceTypes(); } else if (def instanceof RuntimeChildResourceDefinition) { RuntimeChildResourceDefinition resDef = (RuntimeChildResourceDefinition) def; resourceTypes = resDef.getResourceTypes(); } else { throw new ConfigurationException("Property " + paramPath + " of type " + myResourceName + " is not a resource: " + def.getClass()); } resourceId = ref.getValue(); } else { RuntimeResourceDefinition resDef = myContext.getResourceDefinition(ref.getResourceType()); resourceTypes = new ArrayList<Class<? extends IBaseResource>>(1); resourceTypes.add(resDef.getImplementingClass()); resourceId = ref.getIdPart(); } boolean foundChainMatch = false; String chain = ref.getChain(); String remainingChain = null; int chainDotIndex = chain.indexOf('.'); if (chainDotIndex != -1) { remainingChain = chain.substring(chainDotIndex + 1); chain = chain.substring(0, chainDotIndex); } for (Class<? extends IBaseResource> nextType : resourceTypes) { RuntimeResourceDefinition typeDef = myContext.getResourceDefinition(nextType); IFhirResourceDao<?> dao = myCallingDao.getDao(nextType); if (dao == null) { ourLog.debug("Don't have a DAO for type {}", nextType.getSimpleName()); continue; } int qualifierIndex = chain.indexOf(':'); String qualifier = null; if (qualifierIndex != -1) { qualifier = chain.substring(qualifierIndex); chain = chain.substring(0, qualifierIndex); } boolean isMeta = BaseHapiFhirDao.RESOURCE_META_PARAMS.containsKey(chain); RuntimeSearchParam param = null; if (!isMeta) { param = typeDef.getSearchParam(chain); if (param == null) { ourLog.debug("Type {} doesn't have search param {}", nextType.getSimpleName(), param); continue; } } IQueryParameterType chainValue; if (remainingChain != null) { if (param == null || param.getParamType() != RestSearchParameterTypeEnum.REFERENCE) { ourLog.debug("Type {} parameter {} is not a reference, can not chain {}", new Object[] { nextType.getSimpleName(), chain, remainingChain }); continue; } chainValue = new ReferenceParam(); chainValue.setValueAsQueryToken(myContext, theParamName, qualifier, resourceId); ((ReferenceParam) chainValue).setChain(remainingChain); } else if (isMeta) { IQueryParameterType type = BaseHapiFhirDao.newInstanceType(chain); type.setValueAsQueryToken(myContext, theParamName, qualifier, resourceId); chainValue = type; } else { chainValue = toParameterType(param, qualifier, resourceId); } foundChainMatch = true; Set<Long> pids = dao.searchForIds(chain, chainValue); if (pids.isEmpty()) { continue; } Predicate eq = from.get("myTargetResourcePid").in(pids); codePredicates.add(eq); } if (!foundChainMatch) { throw new InvalidRequestException( myContext.getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "invalidParameterChain", theParamName + '.' + ref.getChain())); } } } else { throw new IllegalArgumentException( "Invalid token type (expecting ReferenceParam): " + params.getClass()); } } List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(createResourceLinkPathPredicate(theParamName, from)); predicates.add(builder.or(toArray(codePredicates))); createPredicateResourceId(builder, cq, predicates, from.get("mySourceResourcePid").as(Long.class)); createPredicateLastUpdatedForResourceLink(builder, from, predicates); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); doSetPids(new HashSet<Long>(q.getResultList())); }
From source file:org.apache.rave.portal.repository.impl.JpaWidgetRepository.java
private Predicate[] getStatusAndTypeAndFreeTextPredicates(CriteriaBuilder cb, Root<JpaWidget> widgetType, WidgetStatus widgetStatus, String type, String searchTerm) { List<Predicate> predicates = new ArrayList<Predicate>(); if (StringUtils.isNotBlank(searchTerm)) { predicates.add(/*from w w w .ja v a2 s.c o m*/ cb.or(cb.like(cb.lower(getTitleField(widgetType)), getLowercaseWildcardSearchTerm(searchTerm)), cb.like(cb.lower(getDescriptionField(widgetType)), getLowercaseWildcardSearchTerm(searchTerm)))); } if (StringUtils.isNotBlank(type)) { predicates.add(cb.and(cb.equal(getTypeField(widgetType), type))); } if (widgetStatus != null) { predicates.add(cb.and(cb.equal(getWidgetStatusField(widgetType), widgetStatus))); } return predicates.toArray(new Predicate[predicates.size()]); }
From source file:org.easy.criteria.CriteriaComposer.java
/** * @param criteriaBuilder/*w ww.j av a2 s . co m*/ * @param out */ @SuppressWarnings("unchecked") protected void generateHaving(final CriteriaBuilder criteriaBuilder, final List<Predicate> out) { // log.debug("generateHaving :"); Preconditions.checkNotNull(out); Preconditions.checkNotNull(criteriaBuilder); Preconditions.checkNotNull(root); if (_joins != null && _joins.size() > 0) { Set<Entry<JoinContainer<E>, CriteriaComposer<?>>> allSetJoins = _joins.entrySet(); for (Entry<JoinContainer<E>, CriteriaComposer<?>> joinEntry : allSetJoins) { CriteriaComposer<?> subCriteria = joinEntry.getValue(); if (subCriteria != null) subCriteria.generateHaving(criteriaBuilder, out); } } if (_havings != null) { List<Predicate> andPredicates = new ArrayList<Predicate>(0); List<Predicate> orPredicates = new ArrayList<Predicate>(0); LogicOperator lastOperator = LogicOperator.NONE; for (HavingContainer<E> havingContainer : _havings) { @SuppressWarnings("rawtypes") Expression expression = null; switch (havingContainer.function) { case COUNT: expression = criteriaBuilder.count(root.get(havingContainer.attribute)); break; case AVG: expression = criteriaBuilder.avg(root.get(havingContainer.attribute)); break; case SUM: expression = criteriaBuilder.sum(root.get(havingContainer.attribute)); break; case MAX: expression = criteriaBuilder.max(root.get(havingContainer.attribute)); break; case MIN: expression = criteriaBuilder.min(root.get(havingContainer.attribute)); break; } Predicate predicate = ComparisonOperatorProcessor.process(criteriaBuilder, expression, havingContainer.comparisionOperator, havingContainer.value); if (havingContainer.notOperator != null) predicate = ComparisonOperatorProcessor.negate(criteriaBuilder, predicate); LogicOperator nextOperator = havingContainer.logicOperator; if (nextOperator == LogicOperator.NONE && !nextOperator.equals(lastOperator)) nextOperator = lastOperator; switch (nextOperator) { case AND: case NONE: andPredicates.add(predicate); break; case OR: orPredicates.add(predicate); break; default: throw new java.lang.IllegalStateException( "Unknown operator found " + havingContainer.comparisionOperator.toString()); } lastOperator = nextOperator; } // end for if (andPredicates != null && andPredicates.size() > 0) out.add(criteriaBuilder.and(andPredicates.toArray(new Predicate[andPredicates.size()]))); if (orPredicates != null && orPredicates.size() > 0) out.add(criteriaBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } // end if }
From source file:org.easy.criteria.CriteriaComposer.java
/** * Adds all attributes to match and their values to the predicate. * /* www .j a v a 2s . co m*/ * @param criteriaBuilder * @param out * - predicates */ @SuppressWarnings("unchecked") protected void generateWhere(final CriteriaBuilder criteriaBuilder, final List<Predicate> out) { // log.debug("generateWhereClaus :"); Preconditions.checkNotNull(out); Preconditions.checkNotNull(criteriaBuilder); Preconditions.checkNotNull(root); if (_joins != null && _joins.size() > 0) { Set<Entry<JoinContainer<E>, CriteriaComposer<?>>> allSetJoins = _joins.entrySet(); for (Entry<JoinContainer<E>, CriteriaComposer<?>> joinEntry : allSetJoins) { CriteriaComposer<?> subCriteria = joinEntry.getValue(); if (subCriteria != null) subCriteria.generateWhere(criteriaBuilder, out); } } if (_wheres != null) { List<Predicate> andPredicates = new ArrayList<Predicate>(0); List<Predicate> orPredicates = new ArrayList<Predicate>(0); LogicOperator lastOperator = LogicOperator.NONE; for (WhereContainer<E> where : _wheres) { Predicate predicate = ComparisonOperatorProcessor.process(criteriaBuilder, root.get(where.attribute), where.comparisionOperator, where.value); if (where.notOperator != null) predicate = criteriaBuilder.not(predicate); LogicOperator nextOperator = where.logicOperator; if (nextOperator == LogicOperator.NONE && !nextOperator.equals(lastOperator)) nextOperator = lastOperator; switch (nextOperator) { case AND: case NONE: andPredicates.add(predicate); break; case OR: orPredicates.add(predicate); break; default: throw new java.lang.IllegalStateException( "Unknown operator found " + where.comparisionOperator.toString()); } lastOperator = nextOperator; } // end for if (andPredicates != null && andPredicates.size() > 0) out.add(criteriaBuilder.and(andPredicates.toArray(new Predicate[andPredicates.size()]))); if (orPredicates != null && orPredicates.size() > 0) out.add(criteriaBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } // end if }
From source file:org.finra.herd.dao.impl.AbstractHerdDao.java
/** * Builds a query restriction predicate for the storage. * * @param builder the criteria builder//from w w w . j ava 2 s.c om * @param storageEntity the storage entity that appears in the from clause * @param storagePlatformEntity the storage platform entity that appears in the from clause * @param storageNames the list of storage names where the business object data storage units should be looked for (case-insensitive) * @param storagePlatformType the optional storage platform type, e.g. S3 for Hive DDL. It is ignored when the list of storages is not empty * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storages is not empty or * the storage platform type is specified * * @return the query restriction predicate */ protected Predicate getQueryRestrictionOnStorage(CriteriaBuilder builder, From<?, StorageEntity> storageEntity, From<?, StoragePlatformEntity> storagePlatformEntity, List<String> storageNames, String storagePlatformType, String excludedStoragePlatformType) { List<Predicate> predicates = new ArrayList<>(); // If specified, add restriction on storage. if (!CollectionUtils.isEmpty(storageNames)) { // Add a storage name restriction to the main query where clause. List<String> uppercaseStorageNames = new ArrayList<>(); for (String storageName : storageNames) { uppercaseStorageNames.add(storageName.toUpperCase()); } predicates.add(builder.upper(storageEntity.get(StorageEntity_.name)).in(uppercaseStorageNames)); } else if (StringUtils.isNotBlank(storagePlatformType)) { // Select storage units only from the storages of the specified storage platform type. predicates.add( builder.equal(storagePlatformEntity.get(StoragePlatformEntity_.name), storagePlatformType)); } else if (StringUtils.isNotBlank(excludedStoragePlatformType)) { // Ignore any storages of the excluded storage platform type. predicates.add(builder.notEqual(storagePlatformEntity.get(StoragePlatformEntity_.name), excludedStoragePlatformType)); } return builder.and(predicates.toArray(new Predicate[predicates.size()])); }
From source file:org.finra.herd.dao.impl.AttributeValueListDaoImpl.java
@Override public AttributeValueListEntity getAttributeValueListByKey(AttributeValueListKey attributeValueListKey) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<AttributeValueListEntity> criteria = builder.createQuery(AttributeValueListEntity.class); // The criteria root is the attribute value list. Root<AttributeValueListEntity> attributeValueListEntityRoot = criteria.from(AttributeValueListEntity.class); // Join to the other tables we can filter on. Join<AttributeValueListEntity, NamespaceEntity> namespaceEntityJoin = attributeValueListEntityRoot .join(AttributeValueListEntity_.namespace); // Create the standard restrictions (i.e. the standard where clauses). List<Predicate> predicates = new ArrayList<>(); predicates.add(builder.equal(builder.upper(namespaceEntityJoin.get(NamespaceEntity_.code)), attributeValueListKey.getNamespace().toUpperCase())); predicates// w w w . j a va2 s . c om .add(builder.equal(builder.upper(attributeValueListEntityRoot.get(AttributeValueListEntity_.name)), attributeValueListKey.getAttributeValueListName().toUpperCase())); // Add all clauses to the query. criteria.select(attributeValueListEntityRoot) .where(builder.and(predicates.toArray(new Predicate[predicates.size()]))); // Execute the query and return the results. return executeSingleResultQuery(criteria, String.format( "Found more than one attribute value list with parameters {namespace=\"%s\", attribute_value_name=\"%s\"}.", attributeValueListKey.getNamespace(), attributeValueListKey.getAttributeValueListName())); }