Example usage for javax.persistence.criteria Path as

List of usage examples for javax.persistence.criteria Path as

Introduction

In this page you can find the example usage for javax.persistence.criteria Path as.

Prototype

<X> Expression<X> as(Class<X> type);

Source Link

Document

Perform a typecast upon the expression, returning a new expression object.

Usage

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateNumber(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }/*from   w  w w.j  a 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 (params instanceof NumberParam) {
            NumberParam param = (NumberParam) params;

            BigDecimal value = param.getValue();
            if (value == null) {
                return thePids;
            }

            Path<Object> fromObj = from.get("myValue");
            if (param.getComparator() == null) {
                double mul = value.doubleValue() * 1.01;
                double low = value.doubleValue() - mul;
                double high = value.doubleValue() + mul;
                Predicate lowPred = builder.ge(fromObj.as(Long.class), low);
                Predicate highPred = builder.le(fromObj.as(Long.class), high);
                codePredicates.add(builder.and(lowPred, highPred));
            } else {
                switch (param.getComparator()) {
                case GREATERTHAN:
                    codePredicates.add(builder.greaterThan(fromObj.as(BigDecimal.class), value));
                    break;
                case GREATERTHAN_OR_EQUALS:
                    codePredicates.add(builder.ge(fromObj.as(BigDecimal.class), value));
                    break;
                case LESSTHAN:
                    codePredicates.add(builder.lessThan(fromObj.as(BigDecimal.class), value));
                    break;
                case LESSTHAN_OR_EQUALS:
                    codePredicates.add(builder.le(fromObj.as(BigDecimal.class), value));
                    break;
                }
            }
        } else {
            throw new IllegalArgumentException("Invalid token type: " + params.getClass());
        }

    }

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());
}

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;//from w  w  w. ja  v  a 2  s.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:org.apache.cxf.jaxrs.ext.search.jpa.AbstractJPATypedQueryVisitor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate doBuildPredicate(ConditionType ct, Path<?> path, Class<?> valueClazz, Object value) {

    Class<? extends Comparable> clazz = (Class<? extends Comparable>) valueClazz;
    Expression<? extends Comparable> exp = path.as(clazz);

    Predicate pred = null;//from  w  ww.  j av  a 2 s.co m
    switch (ct) {
    case GREATER_THAN:
        pred = builder.greaterThan(exp, clazz.cast(value));
        break;
    case EQUALS:
        if (clazz.equals(String.class)) {
            String theValue = value.toString();
            if (theValue.contains("*")) {
                theValue = ((String) value).replaceAll("\\*", "");
            }
            pred = builder.like((Expression<String>) exp, "%" + theValue + "%");
        } else {
            pred = builder.equal(exp, clazz.cast(value));
        }
        break;
    case NOT_EQUALS:
        pred = builder.notEqual(exp, clazz.cast(value));
        break;
    case LESS_THAN:
        pred = builder.lessThan(exp, clazz.cast(value));
        break;
    case LESS_OR_EQUALS:
        pred = builder.lessThanOrEqualTo(exp, clazz.cast(value));
        break;
    case GREATER_OR_EQUALS:
        pred = builder.greaterThanOrEqualTo(exp, clazz.cast(value));
        break;
    default:
        break;
    }
    return pred;
}

From source file:org.broadleafcommerce.admin.server.service.handler.SkuCustomPersistenceHandler.java

public void applyProductOptionValueCriteria(List<FilterMapping> filterMappings, CriteriaTransferObject cto,
        PersistencePackage persistencePackage, String skuPropertyPrefix) {

    //if the front
    final List<Long> productOptionValueFilterIDs = new ArrayList<Long>();
    for (String filterProperty : cto.getCriteriaMap().keySet()) {
        if (filterProperty.startsWith(PRODUCT_OPTION_FIELD_PREFIX)) {
            FilterAndSortCriteria criteria = cto.get(filterProperty);
            productOptionValueFilterIDs.add(Long.parseLong(criteria.getFilterValues().get(0)));
        }/* w  w  w  .  ja v a 2 s .c  o  m*/
    }

    //also determine if there is a consolidated POV query
    final List<String> productOptionValueFilterValues = new ArrayList<String>();
    FilterAndSortCriteria consolidatedCriteria = cto.get(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
    if (!consolidatedCriteria.getFilterValues().isEmpty()) {
        //the criteria in this case would be a semi-colon delimeter value list
        productOptionValueFilterValues.addAll(Arrays.asList(StringUtils
                .split(consolidatedCriteria.getFilterValues().get(0), CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER)));
    }

    if (productOptionValueFilterIDs.size() > 0) {
        FilterMapping filterMapping = new FilterMapping()
                .withFieldPath(new FieldPath().withTargetProperty(StringUtils.isEmpty(skuPropertyPrefix) ? ""
                        : skuPropertyPrefix + ".productOptionValueXrefs.productOptionValue.id"))
                .withDirectFilterValues(productOptionValueFilterIDs)
                .withRestriction(new Restriction().withPredicateProvider(new PredicateProvider() {
                    @Override
                    public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
                            From root, String ceilingEntity, String fullPropertyName, Path explicitPath,
                            List directValues) {
                        return explicitPath.as(Long.class).in(directValues);
                    }
                }));
        filterMappings.add(filterMapping);
    }
    if (productOptionValueFilterValues.size() > 0) {
        FilterMapping filterMapping = new FilterMapping()
                .withFieldPath(new FieldPath().withTargetProperty(StringUtils.isEmpty(skuPropertyPrefix) ? ""
                        : skuPropertyPrefix + ".productOptionValueXrefs.productOptionValue.attributeValue"))
                .withDirectFilterValues(productOptionValueFilterValues)
                .withRestriction(new Restriction().withPredicateProvider(new PredicateProvider() {
                    @Override
                    public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
                            From root, String ceilingEntity, String fullPropertyName, Path explicitPath,
                            List directValues) {
                        return explicitPath.as(String.class).in(directValues);
                    }
                }));
        filterMappings.add(filterMapping);
    }
}

From source file:org.sparkcommerce.admin.server.service.handler.SkuCustomPersistenceHandler.java

public static void applyProductOptionValueCriteria(List<FilterMapping> filterMappings,
        CriteriaTransferObject cto, PersistencePackage persistencePackage, String skuPropertyPrefix) {

    //if the front
    final List<Long> productOptionValueFilterIDs = new ArrayList<Long>();
    for (String filterProperty : cto.getCriteriaMap().keySet()) {
        if (filterProperty.startsWith(PRODUCT_OPTION_FIELD_PREFIX)) {
            FilterAndSortCriteria criteria = cto.get(filterProperty);
            productOptionValueFilterIDs.add(Long.parseLong(criteria.getFilterValues().get(0)));
        }/*from   ww w.j a  v a2 s.c  o m*/
    }

    //also determine if there is a consolidated POV query
    final List<String> productOptionValueFilterValues = new ArrayList<String>();
    FilterAndSortCriteria consolidatedCriteria = cto.get(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME);
    if (!consolidatedCriteria.getFilterValues().isEmpty()) {
        //the criteria in this case would be a semi-colon delimeter value list
        productOptionValueFilterValues.addAll(Arrays.asList(StringUtils
                .split(consolidatedCriteria.getFilterValues().get(0), CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER)));
    }

    if (productOptionValueFilterIDs.size() > 0) {
        FilterMapping filterMapping = new FilterMapping()
                .withFieldPath(new FieldPath().withTargetProperty(StringUtils.isEmpty(skuPropertyPrefix) ? ""
                        : skuPropertyPrefix + "productOptionValues.id"))
                .withDirectFilterValues(productOptionValueFilterIDs)
                .withRestriction(new Restriction().withPredicateProvider(new PredicateProvider() {
                    @Override
                    public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
                            From root, String ceilingEntity, String fullPropertyName, Path explicitPath,
                            List directValues) {
                        return explicitPath.as(Long.class).in(directValues);
                    }
                }));
        filterMappings.add(filterMapping);
    }
    if (productOptionValueFilterValues.size() > 0) {
        FilterMapping filterMapping = new FilterMapping()
                .withFieldPath(new FieldPath().withTargetProperty(StringUtils.isEmpty(skuPropertyPrefix) ? ""
                        : skuPropertyPrefix + "productOptionValues.attributeValue"))
                .withDirectFilterValues(productOptionValueFilterValues)
                .withRestriction(new Restriction().withPredicateProvider(new PredicateProvider() {
                    @Override
                    public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
                            From root, String ceilingEntity, String fullPropertyName, Path explicitPath,
                            List directValues) {
                        return explicitPath.as(String.class).in(directValues);
                    }
                }));
        filterMappings.add(filterMapping);
    }
}