Example usage for javax.persistence.criteria From get

List of usage examples for javax.persistence.criteria From get

Introduction

In this page you can find the example usage for javax.persistence.criteria From get.

Prototype

<Y> Path<Y> get(SingularAttribute<? super X, Y> attribute);

Source Link

Document

Create a path corresponding to the referenced single-valued attribute.

Usage

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

private void createSort(CriteriaBuilder theBuilder, Root<ResourceTable> theFrom, SortSpec theSort,
        List<Order> theOrders, List<Predicate> thePredicates) {
    if (theSort == null || isBlank(theSort.getParamName())) {
        return;/*from   w w  w . ja  v a 2  s . c  o  m*/
    }

    if ("_id".equals(theSort.getParamName())) {
        From<?, ?> forcedIdJoin = theFrom.join("myForcedId", JoinType.LEFT);
        if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
            theOrders.add(theBuilder.asc(forcedIdJoin.get("myForcedId")));
            theOrders.add(theBuilder.asc(theFrom.get("myId")));
        } else {
            theOrders.add(theBuilder.desc(forcedIdJoin.get("myForcedId")));
            theOrders.add(theBuilder.desc(theFrom.get("myId")));
        }

        createSort(theBuilder, theFrom, theSort.getChain(), theOrders, null);
        return;
    }

    RuntimeResourceDefinition resourceDef = getContext().getResourceDefinition(myResourceType);
    RuntimeSearchParam param = resourceDef.getSearchParam(theSort.getParamName());
    if (param == null) {
        throw new InvalidRequestException("Unknown sort parameter '" + theSort.getParamName() + "'");
    }

    String joinAttrName;
    String sortAttrName;

    switch (param.getParamType()) {
    case STRING:
        joinAttrName = "myParamsString";
        sortAttrName = "myValueExact";
        break;
    case DATE:
        joinAttrName = "myParamsDate";
        sortAttrName = "myValueLow";
        break;
    default:
        throw new NotImplementedException("This server does not support _sort specifications of type "
                + param.getParamType() + " - Can't serve _sort=" + theSort.getParamName());
    }

    From<?, ?> stringJoin = theFrom.join(joinAttrName, JoinType.INNER);
    // Predicate p = theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName());
    // Predicate pn = theBuilder.isNull(stringJoin.get("myParamName"));
    // thePredicates.add(theBuilder.or(p, pn));

    if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
        theOrders.add(theBuilder.asc(stringJoin.get(sortAttrName)));
    } else {
        theOrders.add(theBuilder.desc(stringJoin.get(sortAttrName)));
    }

    createSort(theBuilder, theFrom, theSort.getChain(), theOrders, null);
}

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

private void createSort(CriteriaBuilder theBuilder, Root<ResourceTable> theFrom, SortSpec theSort,
        List<Order> theOrders, List<Predicate> thePredicates) {
    if (theSort == null || isBlank(theSort.getParamName())) {
        return;//  w ww .jav a 2 s.  co  m
    }

    if (BaseResource.SP_RES_ID.equals(theSort.getParamName())) {
        From<?, ?> forcedIdJoin = theFrom.join("myForcedId", JoinType.LEFT);
        if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
            theOrders.add(theBuilder.asc(forcedIdJoin.get("myForcedId")));
            theOrders.add(theBuilder.asc(theFrom.get("myId")));
        } else {
            theOrders.add(theBuilder.desc(forcedIdJoin.get("myForcedId")));
            theOrders.add(theBuilder.desc(theFrom.get("myId")));
        }

        createSort(theBuilder, theFrom, theSort.getChain(), theOrders, thePredicates);
        return;
    }

    if (Constants.PARAM_LASTUPDATED.equals(theSort.getParamName())) {
        if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
            theOrders.add(theBuilder.asc(theFrom.get("myUpdated")));
        } else {
            theOrders.add(theBuilder.desc(theFrom.get("myUpdated")));
        }

        createSort(theBuilder, theFrom, theSort.getChain(), theOrders, thePredicates);
        return;
    }

    RuntimeSearchParam param = getSearchParam(theSort.getParamName());
    if (param == null) {
        throw new InvalidRequestException("Unknown sort parameter '" + theSort.getParamName() + "'");
    }

    String joinAttrName;
    String[] sortAttrName;

    switch (param.getParamType()) {
    case STRING:
        joinAttrName = "myParamsString";
        sortAttrName = new String[] { "myValueExact" };
        break;
    case DATE:
        joinAttrName = "myParamsDate";
        sortAttrName = new String[] { "myValueLow" };
        break;
    case REFERENCE:
        joinAttrName = "myResourceLinks";
        sortAttrName = new String[] { "myTargetResourcePid" };
        break;
    case TOKEN:
        joinAttrName = "myParamsToken";
        sortAttrName = new String[] { "mySystem", "myValue" };
        break;
    case NUMBER:
        joinAttrName = "myParamsNumber";
        sortAttrName = new String[] { "myValue" };
        break;
    case URI:
        joinAttrName = "myParamsUri";
        sortAttrName = new String[] { "myUri" };
        break;
    case QUANTITY:
        joinAttrName = "myParamsQuantity";
        sortAttrName = new String[] { "myValue" };
        break;
    default:
        throw new InvalidRequestException("This server does not support _sort specifications of type "
                + param.getParamType() + " - Can't serve _sort=" + theSort.getParamName());
    }

    From<?, ?> stringJoin = theFrom.join(joinAttrName, JoinType.INNER);

    if (param.getParamType() == RestSearchParameterTypeEnum.REFERENCE) {
        thePredicates.add(stringJoin.get("mySourcePath").as(String.class).in(param.getPathsSplit()));
    } else {
        thePredicates.add(theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName()));
    }

    // Predicate p = theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName());
    // Predicate pn = theBuilder.isNull(stringJoin.get("myParamName"));
    // thePredicates.add(theBuilder.or(p, pn));

    for (String next : sortAttrName) {
        if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
            theOrders.add(theBuilder.asc(stringJoin.get(next)));
        } else {
            theOrders.add(theBuilder.desc(stringJoin.get(next)));
        }
    }

    createSort(theBuilder, theFrom, theSort.getChain(), theOrders, thePredicates);
}

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

private Predicate createPredicateString(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,//from   w w w  .java2  s . c o  m
        From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> theFrom) {
    String rawSearchTerm;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        if (!id.isText()) {
            throw new IllegalStateException("Trying to process a text search on a non-text token parameter");
        }
        rawSearchTerm = id.getValue();
    } else if (theParameter instanceof StringParam) {
        StringParam id = (StringParam) theParameter;
        rawSearchTerm = id.getValue();
    } else if (theParameter instanceof IPrimitiveDatatype<?>) {
        IPrimitiveDatatype<?> id = (IPrimitiveDatatype<?>) theParameter;
        rawSearchTerm = id.getValueAsString();
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (rawSearchTerm.length() > ResourceIndexedSearchParamString.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has length ("
                + rawSearchTerm.length() + ") that is longer than maximum allowed ("
                + ResourceIndexedSearchParamString.MAX_LENGTH + "): " + rawSearchTerm);
    }

    String likeExpression = normalizeString(rawSearchTerm);
    likeExpression = likeExpression.replace("%", "[%]") + "%";

    Predicate singleCode = theBuilder.like(theFrom.get("myValueNormalized").as(String.class), likeExpression);
    if (theParameter instanceof StringParam && ((StringParam) theParameter).isExact()) {
        Predicate exactCode = theBuilder.equal(theFrom.get("myValueExact"), rawSearchTerm);
        singleCode = theBuilder.and(singleCode, exactCode);
    }
    return singleCode;
}

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

private Predicate createPredicateQuantity(CriteriaBuilder theBuilder,
        From<ResourceIndexedSearchParamQuantity, ResourceIndexedSearchParamQuantity> theFrom,
        IQueryParameterType theParam) {// w  ww  .ja  v a2  s  .  co m
    String systemValue;
    String unitsValue;
    ParamPrefixEnum cmpValue;
    BigDecimal valueValue;
    String valueString;

    if (theParam instanceof BaseQuantityDt) {
        BaseQuantityDt param = (BaseQuantityDt) theParam;
        systemValue = param.getSystemElement().getValueAsString();
        unitsValue = param.getUnitsElement().getValueAsString();
        cmpValue = ParamPrefixEnum.forDstu1Value(param.getComparatorElement().getValueAsString());
        valueValue = param.getValueElement().getValue();
        valueString = param.getValueElement().getValueAsString();
    } else if (theParam instanceof QuantityParam) {
        QuantityParam param = (QuantityParam) theParam;
        systemValue = param.getSystem();
        unitsValue = param.getUnits();
        cmpValue = param.getPrefix();
        valueValue = param.getValue();
        valueString = param.getValueAsString();
    } else {
        throw new IllegalArgumentException("Invalid quantity type: " + theParam.getClass());
    }

    Predicate system = null;
    if (!isBlank(systemValue)) {
        system = theBuilder.equal(theFrom.get("mySystem"), systemValue);
    }

    Predicate code = null;
    if (!isBlank(unitsValue)) {
        code = theBuilder.equal(theFrom.get("myUnits"), unitsValue);
    }

    cmpValue = ObjectUtils.defaultIfNull(cmpValue, ParamPrefixEnum.EQUAL);
    final Expression<BigDecimal> path = theFrom.get("myValue");
    String invalidMessageName = "invalidQuantityPrefix";

    Predicate num = createPredicateNumeric(theBuilder, theParam, cmpValue, valueValue, path, invalidMessageName,
            valueString);

    Predicate singleCode;
    if (system == null && code == null) {
        singleCode = num;
    } else if (system == null) {
        singleCode = theBuilder.and(code, num);
    } else if (code == null) {
        singleCode = theBuilder.and(system, num);
    } else {
        singleCode = theBuilder.and(system, code, num);
    }

    return singleCode;
}

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

private Predicate createPredicateToken(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,//from   ww w .  j  a v a  2s  .  c  o  m
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> theFrom) {
    String code;
    String system;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        system = id.getSystem();
        code = id.getValue();
    } else if (theParameter instanceof BaseIdentifierDt) {
        BaseIdentifierDt id = (BaseIdentifierDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = id.getValueElement().getValue();
    } else if (theParameter instanceof BaseCodingDt) {
        BaseCodingDt id = (BaseCodingDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = id.getCodeElement().getValue();
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (system != null && system.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has system (" + system.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + system);
    }
    if (code != null && code.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has code (" + code.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + code);
    }

    ArrayList<Predicate> singleCodePredicates = (new ArrayList<Predicate>());
    if (StringUtils.isNotBlank(system)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("mySystem"), system));
    } else if (system == null) {
        // don't check the system
    } else {
        // If the system is "", we only match on null systems
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("mySystem")));
    }
    if (StringUtils.isNotBlank(code)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("myValue"), code));
    } else {
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("myValue")));
    }
    Predicate singleCode = theBuilder.and(singleCodePredicates.toArray(new Predicate[0]));
    return singleCode;
}

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

private Predicate createPredicateString(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,/*from   ww w. j  a va2  s .c o m*/
        From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> theFrom) {
    String rawSearchTerm;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        if (!id.isText()) {
            throw new IllegalStateException("Trying to process a text search on a non-text token parameter");
        }
        rawSearchTerm = id.getValue();
    } else if (theParameter instanceof StringParam) {
        StringParam id = (StringParam) theParameter;
        rawSearchTerm = id.getValue();
    } else if (theParameter instanceof IPrimitiveDatatype<?>) {
        IPrimitiveDatatype<?> id = (IPrimitiveDatatype<?>) theParameter;
        rawSearchTerm = id.getValueAsString();
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (rawSearchTerm.length() > ResourceIndexedSearchParamString.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has length ("
                + rawSearchTerm.length() + ") that is longer than maximum allowed ("
                + ResourceIndexedSearchParamString.MAX_LENGTH + "): " + rawSearchTerm);
    }

    String likeExpression = BaseHapiFhirDao.normalizeString(rawSearchTerm);
    likeExpression = createLeftMatchLikeExpression(likeExpression);

    Predicate singleCode = theBuilder.like(theFrom.get("myValueNormalized").as(String.class), likeExpression);
    if (theParameter instanceof StringParam && ((StringParam) theParameter).isExact()) {
        Predicate exactCode = theBuilder.equal(theFrom.get("myValueExact"), rawSearchTerm);
        singleCode = theBuilder.and(singleCode, exactCode);
    }
    return singleCode;
}

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

private Predicate createPredicateToken(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,//w w  w  . j a  v a2s .c  om
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> theFrom) {
    String code;
    String system;
    TokenParamModifier modifier = null;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        system = id.getSystem();
        code = (id.getValue());
        modifier = id.getModifier();
    } else if (theParameter instanceof BaseIdentifierDt) {
        BaseIdentifierDt id = (BaseIdentifierDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = (id.getValueElement().getValue());
    } else if (theParameter instanceof BaseCodingDt) {
        BaseCodingDt id = (BaseCodingDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = (id.getCodeElement().getValue());
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (system != null && system.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has system (" + system.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + system);
    }

    if (code != null && code.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has code (" + code.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + code);
    }

    /*
     * Process token modifiers (:in, :below, :above)
     */

    List<VersionIndependentConcept> codes = null;
    if (modifier == TokenParamModifier.IN) {
        codes = myTerminologySvc.expandValueSet(code);
    } else if (modifier == TokenParamModifier.ABOVE) {
        system = determineSystemIfMissing(theParamName, code, system);
        codes = myTerminologySvc.findCodesAbove(system, code);
    } else if (modifier == TokenParamModifier.BELOW) {
        system = determineSystemIfMissing(theParamName, code, system);
        codes = myTerminologySvc.findCodesBelow(system, code);
    }

    if (codes != null) {
        if (codes.isEmpty()) {
            return null;
        }
        List<Predicate> orPredicates = new ArrayList<Predicate>();
        for (VersionIndependentConcept nextCode : codes) {
            Predicate systemPredicate = theBuilder.equal(theFrom.get("mySystem"), nextCode.getSystem());
            Predicate codePredicate = theBuilder.equal(theFrom.get("myValue"), nextCode.getCode());
            orPredicates.add(theBuilder.and(systemPredicate, codePredicate));
        }

        return theBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]));
    }

    /*
     * Ok, this is a normal query
     */

    ArrayList<Predicate> singleCodePredicates = (new ArrayList<Predicate>());
    if (StringUtils.isNotBlank(system)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("mySystem"), system));
    } else if (system == null) {
        // don't check the system
    } else {
        // If the system is "", we only match on null systems
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("mySystem")));
    }

    if (StringUtils.isNotBlank(code)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("myValue"), code));
    } else {
        /*
         * As of HAPI FHIR 1.5, if the client searched for a token with a system but no specified value this means to
         * match all tokens with the given value.
         * 
         * I'm not sure I agree with this, but hey.. FHIR-I voted and this was the result :)
         */
        // singleCodePredicates.add(theBuilder.isNull(theFrom.get("myValue")));
    }

    Predicate singleCode = theBuilder.and(toArray(singleCodePredicates));
    return singleCode;
}

From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java

/**
 * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.ForwardPropertyStep)
 */// w w w .  j  ava2 s  .  c  om
@Override
public void visit(ForwardPropertyStep node) {
    if (node.getPropertyQName() != null) {
        QName property = node.getPropertyQName();
        if (property.getNamespaceURI() == null || "".equals(property.getNamespaceURI()))
            property = new QName(ArtificerConstants.SRAMP_NS, property.getLocalPart());

        if (property.getNamespaceURI().equals(ArtificerConstants.SRAMP_NS)) {
            if (corePropertyMap.containsKey(property)) {
                propertyContext = corePropertyMap.get(property);
                customPropertySubquery = null;
            } else {
                // Note: Typically, you'd expect to see a really simple MapJoin w/ key and value predicates.
                // However, *negation* ("not()") is needed and is tricky when just using a join.  Instead, use
                // an "a1.id in (select a2.id from ArtificerArtifact a2 [map join and predicates)" -- easily negated.

                customPropertySubquery = query.subquery(ArtificerArtifact.class);
                From customPropertyFrom = customPropertySubquery.from(ArtificerArtifact.class);
                Join customPropertyJoin = customPropertyFrom.join("properties");
                customPropertySubquery.select(customPropertyFrom.get("id"));
                customPropertyPredicates = new ArrayList<>();
                customPropertyPredicates
                        .add(criteriaBuilder.equal(customPropertyFrom.get("id"), from.get("id")));
                customPropertyPredicates
                        .add(criteriaBuilder.equal(customPropertyJoin.get("key"), property.getLocalPart()));
                customPropertyValuePath = customPropertyJoin.get("value");
                predicates.add(criteriaBuilder.exists(customPropertySubquery));
                propertyContext = null;
            }
        } else {
            throw new RuntimeException(
                    Messages.i18n.format("XP_INVALID_PROPERTY_NS", property.getNamespaceURI()));
        }
    }
}

From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java

/**
 * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.FunctionCall)
 *///  www.j a  va2s . c om
@Override
public void visit(FunctionCall node) {
    if (ArtificerConstants.SRAMP_NS.equals(node.getFunctionName().getNamespaceURI())) {
        if (node.getFunctionName().equals(CLASSIFIED_BY_ALL_OF)) {
            visitClassifications(node, false, true);
        } else if (node.getFunctionName().equals(CLASSIFIED_BY_ANY_OF)) {
            visitClassifications(node, true, true);
        } else if (node.getFunctionName().equals(EXACTLY_CLASSIFIED_BY_ALL_OF)) {
            visitClassifications(node, false, false);
        } else if (node.getFunctionName().equals(EXACTLY_CLASSIFIED_BY_ANY_OF)) {
            visitClassifications(node, true, false);
        } else if (node.getFunctionName().equals(GET_RELATIONSHIP_ATTRIBUTE)) {
            String otherAttributeKey = reduceStringLiteralArgument(node.getArguments().get(1));
            // Ex. query: /s-ramp/wsdl/WsdlDocument[someRelationship[s-ramp:getRelationshipAttribute(., 'someAttribute') = 'true']]
            // Note that the predicate function needs to add a condition on the relationship selector itself, *not*
            // the artifact targeted by the relationship.
            customPropertySubquery = query.subquery(ArtificerRelationship.class);
            From customPropertyFrom = customPropertySubquery.from(ArtificerRelationship.class);
            MapJoin customPropertyJoin = customPropertyFrom.joinMap("otherAttributes");
            customPropertySubquery.select(customPropertyFrom.get("id"));
            customPropertyPredicates = new ArrayList<>();
            customPropertyPredicates
                    .add(criteriaBuilder.equal(customPropertyFrom.get("id"), relationshipFrom.get("id")));
            customPropertyPredicates.add(criteriaBuilder.equal(customPropertyJoin.key(), otherAttributeKey));
            customPropertyValuePath = customPropertyJoin.value();
            predicates.add(criteriaBuilder.exists(customPropertySubquery));
            propertyContext = null;
        } else if (node.getFunctionName().equals(GET_TARGET_ATTRIBUTE)) {
            String otherAttributeKey = reduceStringLiteralArgument(node.getArguments().get(1));
            // Ex. query: /s-ramp/wsdl/WsdlDocument[someRelationship[s-ramp:getTargetAttribute(., 'someAttribute') = 'true']]
            // Note that the predicate function needs to add a condition on the relationship target selector itself, *not*
            // the artifact targeted by the relationship.
            customPropertySubquery = query.subquery(ArtificerTarget.class);
            From customPropertyFrom = customPropertySubquery.from(ArtificerTarget.class);
            MapJoin customPropertyJoin = customPropertyFrom.joinMap("otherAttributes");
            customPropertySubquery.select(customPropertyFrom.get("id"));
            customPropertyPredicates = new ArrayList<>();
            customPropertyPredicates
                    .add(criteriaBuilder.equal(customPropertyFrom.get("id"), targetFrom.get("id")));
            customPropertyPredicates.add(criteriaBuilder.equal(customPropertyJoin.key(), otherAttributeKey));
            customPropertyValuePath = customPropertyJoin.value();
            predicates.add(criteriaBuilder.exists(customPropertySubquery));
            propertyContext = null;
        } else {
            if (node.getFunctionName().getLocalPart().equals("matches")
                    || node.getFunctionName().getLocalPart().equals("not")) {
                throw new RuntimeException(
                        Messages.i18n.format("XP_BAD_FUNC_NS", node.getFunctionName().getLocalPart()));
            }
            throw new RuntimeException(
                    Messages.i18n.format("XP_FUNC_NOT_SUPPORTED", node.getFunctionName().toString()));
        }
    } else if (MATCHES.equals(node.getFunctionName())) {
        if (node.getArguments().size() != 2) {
            throw new RuntimeException(
                    Messages.i18n.format("XP_MATCHES_FUNC_NUM_ARGS_ERROR", node.getArguments().size()));
        }
        Argument attributeArg = node.getArguments().get(0);
        Argument patternArg = node.getArguments().get(1);

        String pattern = reduceStringLiteralArgument(patternArg);

        if (isFullTextSearch(attributeArg)) {
            fullTextSearch(pattern);
        } else {
            pattern = pattern.replace(".*", "%"); // the only valid wildcard
            ForwardPropertyStep attribute = reducePropertyArgument(attributeArg);
            attribute.accept(this);
            like(propertyContext, pattern);
        }
    } else if (NOT.equals(node.getFunctionName())) {
        if (node.getArguments().size() != 1) {
            throw new RuntimeException(
                    Messages.i18n.format("XP_NOT_FUNC_NUM_ARGS_ERROR", node.getArguments().size()));
        }

        Argument argument = node.getArguments().get(0);
        if (argument.getExpr() != null) {
            argument.getExpr().accept(this);
            // Should have resulted in only 1 constraint -- negate it and re-add
            Predicate predicate = predicates.remove(predicates.size() - 1);
            predicates.add(criteriaBuilder.not(predicate));
        } else {
            // TODO: When would not() be given a literal?  That's what this implies.  As-is, it won't be negated...
            argument.accept(this);
        }
    } else {
        throw new RuntimeException(
                Messages.i18n.format("XP_FUNCTION_NOT_SUPPORTED", node.getFunctionName().toString()));
    }
}

From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java

/**
 * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.SubartifactSet)
 *//*from  w  w  w .ja v  a2s.com*/
@Override
public void visit(SubartifactSet node) {
    if (node.getFunctionCall() != null) {
        node.getFunctionCall().accept(this);
    } else if (node.getRelationshipPath() != null) {
        From oldRootContext = from;

        if (node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("relatedDocument")) {
            // derivedFrom
            // TODO: Should this really be LEFT?
            from = from.join("derivedFrom", JoinType.LEFT);

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }
        } else if (node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("expandedFromDocument")
                || node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("expandedFromArchive")) {
            // expandedFrom
            from = from.join("expandedFrom");

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }
        } else {
            // Relationship within a predicate.
            // Create a subquery and 'exists' conditional.  The subquery is much easier to handle, later on, if this
            // predicate is negated, as opposed to removing the inner join or messing with left joins.

            List<Predicate> oldPredicates = predicates;
            predicates = new ArrayList<>();

            Subquery relationshipSubquery = query.subquery(ArtificerRelationship.class);
            relationshipFrom = relationshipSubquery.from(ArtificerRelationship.class);
            targetFrom = relationshipFrom.join("targets");
            relationshipSubquery.select(relationshipFrom.get("id"));

            Join relationshipOwnerJoin = relationshipFrom.join("owner");
            predicates.add(criteriaBuilder.equal(relationshipOwnerJoin.get("id"), oldRootContext.get("id")));

            from = relationshipFrom;

            // process constraints on the relationship itself
            node.getRelationshipPath().accept(this);

            // context now needs to be the relationship targets

            from = targetFrom.join("target");

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }

            // Add predicates to subquery
            relationshipSubquery.where(compileAnd(predicates));

            predicates = oldPredicates;

            // Add 'exists' predicate (using subquery) to original list
            predicates.add(criteriaBuilder.exists(relationshipSubquery));
        }

        // restore the original selector (since the relationship was in a predicate, not a path)
        from = oldRootContext;

        if (node.getSubartifactSet() != null) {
            throw new RuntimeException(Messages.i18n.format("XP_MULTILEVEL_SUBARTYSETS_NOT_SUPPORTED"));
        }
    }
}