repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMemberOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMemberOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException.MessageKeys.NOT_ALLOWED_MEMBER;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Path;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
public class JPAMemberOperator implements JPAOperator {
private static final Log LOGGER = LogFactory.getLog(JPAMemberOperator.class);
private final Member member;
private final From<?, ?> root;
private final JPAAssociationPath association;
private final JPAPath attributePath;
JPAMemberOperator(final From<?, ?> parent, final Member member, final JPAAssociationPath association,
final List<String> list, final JPAPath attributePath) throws ODataApplicationException {
super();
this.member = member;
this.root = parent;
this.association = association;
this.attributePath = attributePath;
checkGroup(list);
}
public JPAAttribute determineAttribute() {
return attributePath == null ? null : attributePath.getLeaf();
}
@Override
public Path<?> get() throws ODataApplicationException {
return attributePath == null ? null : determineCriteriaPath(attributePath);
}
public Member getMember() {
return member;
}
@Override
public String getName() {
return member.toString();
}
private Path<?> determineCriteriaPath(final JPAPath selectItemPath) throws ODataJPAFilterException {
Path<?> path = root;
for (final JPAElement jpaPathElement : selectItemPath.getPath()) {
if (jpaPathElement instanceof JPADescriptionAttribute) {
path = determineDescriptionCriteriaPath(selectItemPath, path, jpaPathElement);
} else if (jpaPathElement instanceof final JPACollectionAttribute collectionAttribute) {
if (!collectionAttribute.isComplex()) try {
path = path.get(collectionAttribute.getTargetAttribute().getInternalName());
} catch (final ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
} else {
path = path.get(jpaPathElement.getInternalName());
}
}
return path;
}
private Path<?> determineDescriptionCriteriaPath(final JPAPath selectItemPath, Path<?> path,
final JPAElement jpaPathElement) {
final Set<?> allJoins = root.getJoins();
final Iterator<?> iterator = allJoins.iterator();
while (iterator.hasNext()) {
Join<?, ?> join = (Join<?, ?>) iterator.next();
if (join.getAlias() != null && join.getAlias().equals(selectItemPath.getAlias())) {
final Set<?> subJoins = join.getJoins();
for (final Object sub : subJoins) {
// e.g. "Organizations?$filter=Address/RegionName eq 'Kalifornien'
// see createFromClause in JPAExecutableQuery
if (((Join<?, ?>) sub).getAlias() != null &&
((Join<?, ?>) sub).getAlias().equals(jpaPathElement.getExternalName())) {
join = (Join<?, ?>) sub;
}
}
path = join.get(((JPADescriptionAttribute) jpaPathElement).getDescriptionAttribute().getInternalName());
break;
}
}
return path;
}
private void checkGroup(final List<String> groups) throws ODataJPAFilterException {
JPAPath orgPath = attributePath;
if (association != null && association.getPathAsString() != null && attributePath != null) {
final JPAAttribute st = ((JPAAttribute) this.association.getPath().get(0));
if (st.isComplex()) {
try {
orgPath = st.getStructuredType().getPath(attributePath.getLeaf().getExternalName());
} catch (final ODataJPAModelException e) {
// Ignore exception and use path
LOGGER.debug("Exception occurred -> use path: " + e.getMessage());
}
}
}
if (orgPath != null && !orgPath.isPartOfGroups(groups))
throw new ODataJPAFilterException(NOT_ALLOWED_MEMBER, HttpStatusCode.FORBIDDEN, orgPath.getAlias());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAAbstractFilter.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAAbstractFilter.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public abstract class JPAAbstractFilter implements JPAFilterComplier, JPAFilterComplierAccess {
final JPAEntityType jpaEntityType;
final VisitableExpression expression;
final JPAAssociationPath association;
JPAAbstractFilter(final JPAEntityType jpaEntityType, final VisitableExpression expression) {
this(jpaEntityType, expression, null);
}
JPAAbstractFilter(final JPAEntityType jpaEntityType, final UriInfoResource uriResource,
final JPAAssociationPath association) {
super();
this.jpaEntityType = jpaEntityType;
if (uriResource != null && uriResource.getFilterOption() != null) {
this.expression = uriResource.getFilterOption().getExpression();
} else {
this.expression = null;
}
this.association = association;
}
JPAAbstractFilter(final JPAEntityType jpaEntityType, final VisitableExpression expression,
final JPAAssociationPath association) {
super();
this.jpaEntityType = jpaEntityType;
this.expression = expression;
this.association = association;
}
@Override
public List<JPAPath> getMember() throws ODataApplicationException {
final JPAMemberVisitor visitor = new JPAMemberVisitor(jpaEntityType);
if (expression != null) {
try {
expression.accept(visitor);
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return Collections.unmodifiableList(visitor.get());
} else {
return Collections.emptyList();
}
}
@Override
public JPAAssociationPath getAssociation() {
return association;
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
public final class JPAMethodExpression implements JPAVisitableExpression {
private final MethodKind methodCall;
private final Member member;
private final Literal literal;
public JPAMethodExpression(final Member member, final JPALiteralOperator operand, final MethodKind methodCall) {
super();
this.methodCall = methodCall;
this.member = member;
this.literal = operand != null ? operand.getLiteral() : null;
}
@Override
public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
final List<T> parameters = new ArrayList<>(2);
parameters.add(visitor.visitMember(member));
if (literal != null)
parameters.add(visitor.visitLiteral(literal));
return visitor.visitMethodCall(methodCall, parameters);
}
@Override
public UriInfoResource getMember() {
return member.getResourcePath();
}
@Override
public Literal getLiteral() {
return literal;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPALiteralOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPALiteralOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.query.ExpressionUtility;
public class JPALiteralOperator implements JPAPrimitiveTypeOperator {
private final Literal literal;
private final OData odata;
private final String literalText;
public JPALiteralOperator(final OData odata, final Literal literal) {
this(odata, literal, literal.getText());
}
private JPALiteralOperator(final OData odata, final Literal literal, final String literalText) {
this.literal = literal;
this.odata = odata;
this.literalText = literalText;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAPrimitiveTypeOperator#get()
*/
@Override
public Object get() throws ODataApplicationException {
final EdmPrimitiveType edmType = ((EdmPrimitiveType) literal.getType());
try {
final Object value = edmType.valueOfString(literalText, true, null, null, null, true, edmType.getDefaultType());
if (value instanceof final String asString)
return asString.replace("'", "");
return value;
} catch (final EdmPrimitiveTypeException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* Converts a literal value into system type of attribute
*/
public Object get(final JPAAttribute attribute) throws ODataApplicationException {
return ExpressionUtility.convertValueOnAttribute(odata, attribute, literalText);
}
public Object get(final JPAOperationResultParameter returnType) throws ODataApplicationException {
return ExpressionUtility.convertValueOnFacet(odata, returnType, literalText);
}
public Object get(final JPAParameter jpaParameter) throws ODataApplicationException {
return ExpressionUtility.convertValueOnFacet(odata, jpaParameter, literalText);
}
@Override
public boolean isNull() {
return literal.getText().equals("null");
}
JPALiteralOperator clone(final String prefix, final String postfix) {
return new JPALiteralOperator(odata, literal, "'" + prefix + literal.getText().replace("'", "") + postfix + "'");
}
Literal getLiteral() {
return literal;
}
@Override
public String getName() {
return literal.getText();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMemberVisitor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMemberVisitor.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.edm.EdmEnumType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
import org.apache.olingo.server.api.uri.queryoption.expression.UnaryOperatorKind;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.query.Utility;
final class JPAMemberVisitor implements ExpressionVisitor<JPAPath> {
private final ArrayList<JPAPath> pathList = new ArrayList<>();
private final JPAEntityType jpaEntityType;
public JPAMemberVisitor(final JPAEntityType jpaEntityType) {
super();
this.jpaEntityType = jpaEntityType;
}
public List<JPAPath> get() {
return pathList;
}
@Override
public JPAPath visitBinaryOperator(final BinaryOperatorKind operator, final JPAPath left, final JPAPath right)
throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitBinaryOperator(final BinaryOperatorKind operator, final JPAPath left, final List<JPAPath> right)
throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitUnaryOperator(final UnaryOperatorKind operator, final JPAPath operand)
throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitMethodCall(final MethodKind methodCall, final List<JPAPath> parameters)
throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitLambdaExpression(final String lambdaFunction, final String lambdaVariable,
final org.apache.olingo.server.api.uri.queryoption.expression.Expression expression)
throws ExpressionVisitException,
ODataApplicationException {
return null;
}
@Override
public JPAPath visitLiteral(final Literal literal) throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitMember(final Member member) throws ExpressionVisitException, ODataApplicationException {
final UriResourceKind uriResourceKind =
Optional.of(member.getResourcePath())
.map(UriInfoResource::getUriResourceParts)
.filter(l -> !l.isEmpty())
.map(l -> l.get(0))
.map(UriResource::getKind)
.orElse(null);
if ((uriResourceKind == UriResourceKind.primitiveProperty || uriResourceKind == UriResourceKind.complexProperty)
&& !Utility.hasNavigation(member.getResourcePath().getUriResourceParts())) {
final String path = Utility.determinePropertyNavigationPath(member.getResourcePath().getUriResourceParts());
JPAPath selectItemPath = null;
try {
selectItemPath = jpaEntityType.getPath(path);
} catch (final ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
if (selectItemPath != null) {
pathList.add(selectItemPath);
return selectItemPath;
}
}
return null;
}
@Override
public JPAPath visitAlias(final String aliasName) throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitTypeLiteral(final EdmType type) throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public JPAPath visitLambdaReference(final String variableName) throws ExpressionVisitException,
ODataApplicationException {
return null;
}
@Override
public JPAPath visitEnum(final EdmEnumType type, final List<String> enumValues) throws ExpressionVisitException,
ODataApplicationException {
return null;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodCall.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodCall.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
public interface JPAMethodCall extends JPAOperator {
public MethodKind getFunction();
public JPAOperator getParameter(int index);
/**
* Number of parameter
* @return
*/
public int noParameters();
/**
* Returns extended by a prefix and a suffix<p>
* Main use for method as parameter of of other methods. E.g.: contains(tolower('BE1'))
* @param prefix
* @param suffix
* @return
* @throws ODataApplicationException
*/
public Object get(final String prefix, final String suffix) throws ODataApplicationException;
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAInOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAInOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
public interface JPAInOperator<T, X extends JPAOperator> extends JPAExpressionOperator {
@SuppressWarnings("unchecked")
@Override
BinaryOperatorKind getOperator();
List<X> getFixValues();
Expression<T> getLeft() throws ODataApplicationException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAInOperatorImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAInOperatorImpl.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
public class JPAInOperatorImpl<T, X extends JPAOperator> implements JPAInOperator<T, X> {
private final JPAOperationConverter converter;
private final JPAOperator left;
private final List<X> right;
public JPAInOperatorImpl(final JPAOperationConverter converter,
final JPAOperator left, final List<X> right) {
this.converter = converter;
this.left = left;
this.right = right;
}
@Override
public Expression<Boolean> get() throws ODataApplicationException {
return converter.convert(this);
}
@Override
public String getName() {
return getOperator().name();
}
@Override
public BinaryOperatorKind getOperator() {
return BinaryOperatorKind.IN;
}
@Override
public List<X> getFixValues() {
return right;
}
@SuppressWarnings("unchecked")
@Override
public Expression<T> getLeft() throws ODataApplicationException {
return (Expression<T>) left.get();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodBasedExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodBasedExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
final class JPAMethodBasedExpression extends JPAMethodCallImp implements JPAExpression {
public JPAMethodBasedExpression(final JPAOperationConverter converter, final MethodKind methodCall,
final List<JPAOperator> parameters) {
super(converter, methodCall, parameters);
}
@SuppressWarnings("unchecked")
@Override
public Expression<Boolean> get() throws ODataApplicationException {
return (Expression<Boolean>) super.get();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAOperationConverter.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAOperationConverter.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.function.BiFunction;
import java.util.function.Function;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaBuilder.In;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.UnaryOperatorKind;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
public class JPAOperationConverter {
protected final CriteriaBuilder cb;
private final JPAODataDatabaseOperations dbConverter;
private final JPAODataQueryDirectives directives;
public JPAOperationConverter(final CriteriaBuilder cb, final JPAODataDatabaseOperations converterExtension,
@Nonnull final JPAODataQueryDirectives directives) {
super();
this.cb = cb;
this.dbConverter = converterExtension;
this.dbConverter.setCriteriaBuilder(cb);
this.directives = directives;
}
public final Expression<Long> convert(final JPAAggregationOperationImp jpaOperator) throws ODataApplicationException {
if (jpaOperator.getAggregation() == JPAFilterAggregationType.COUNT)
return cb.count(jpaOperator.getPath());
return dbConverter.convert(jpaOperator);
}
@SuppressWarnings("unchecked")
public final <T extends Number> Expression<T> convert(final JPAArithmeticOperator jpaOperator) // NOSONAR
throws ODataApplicationException {
switch (jpaOperator.getOperator()) {
case ADD:
if (jpaOperator.getRight() instanceof JPALiteralOperator)
return (Expression<T>) cb.sum(jpaOperator.getLeft(cb), jpaOperator.getRightAsNumber(cb));
else
return (Expression<T>) cb.sum(jpaOperator.getLeft(cb), jpaOperator.getRightAsExpression());
case SUB:
if (jpaOperator.getRight() instanceof JPALiteralOperator)
return (Expression<T>) cb.diff(jpaOperator.getLeft(cb), jpaOperator.getRightAsNumber(cb));
else
return (Expression<T>) cb.diff(jpaOperator.getLeft(cb), jpaOperator.getRightAsExpression());
case DIV:
if (jpaOperator.getRight() instanceof JPALiteralOperator)
return (Expression<T>) cb.quot(jpaOperator.getLeft(cb), jpaOperator.getRightAsNumber(cb));
else
return (Expression<T>) cb.quot(jpaOperator.getLeft(cb), jpaOperator.getRightAsExpression());
case MUL:
if (jpaOperator.getRight() instanceof JPALiteralOperator)
return (Expression<T>) cb.prod(jpaOperator.getLeft(cb), jpaOperator.getRightAsNumber(cb));
else
return (Expression<T>) cb.prod(jpaOperator.getLeft(cb), jpaOperator.getRightAsExpression());
case MOD:
if (jpaOperator.getRight() instanceof JPALiteralOperator)
return (Expression<T>) cb.mod(jpaOperator.getLeftAsIntExpression(), Integer.valueOf(jpaOperator
.getRightAsNumber(cb).toString()));
else
return (Expression<T>) cb.mod(jpaOperator.getLeftAsIntExpression(), jpaOperator.getRightAsIntExpression());
default:
return dbConverter.convert(jpaOperator);
}
}
public final Expression<Boolean> convert(final JPABooleanOperatorImp jpaOperator) throws ODataApplicationException {
switch (jpaOperator.getOperator()) {
case AND:
return cb.and(jpaOperator.getLeft(), jpaOperator.getRight());
case OR:
return cb.or(jpaOperator.getLeft(), jpaOperator.getRight());
default:
return dbConverter.convert(jpaOperator);
}
}
@SuppressWarnings({ "unchecked" })
public final Expression<Boolean> convert(@SuppressWarnings("rawtypes") final JPAComparisonOperator jpaOperator)
throws ODataApplicationException {
switch (jpaOperator.getOperator()) {
case EQ:
return equalExpression((left, right) -> (cb.equal(left, right)), (left, right) -> (cb.equal(left, right)),
left -> (cb.isNull(left)), jpaOperator);
case NE:
return equalExpression((left, right) -> (cb.notEqual(left, right)), (left, right) -> (cb.notEqual(left, right)),
left -> (cb.isNotNull(left)), jpaOperator);
case GE:
return comparisonExpression((left, right) -> (cb.greaterThanOrEqualTo(left, right)), (left, right) -> (cb
.greaterThanOrEqualTo(left, right)), jpaOperator);
case GT:
return comparisonExpression((left, right) -> (cb.greaterThan(left, right)), (left, right) -> (cb.greaterThan(
left, right)), jpaOperator);
case LT:
return comparisonExpression((left, right) -> (cb.lessThan(left, right)), (left, right) -> (cb.lessThan(left,
right)), jpaOperator);
case LE:
return comparisonExpression((left, right) -> (cb.lessThanOrEqualTo(left, right)), (left, right) -> (cb
.lessThanOrEqualTo(left, right)), jpaOperator);
default:
return dbConverter.convert(jpaOperator);
}
}
@SuppressWarnings("unchecked")
public final <T, X extends JPAOperator> Expression<Boolean> convert(final JPAInOperator<T, X> jpaOperator)
throws ODataApplicationException {
if (BinaryOperatorKind.IN == jpaOperator.getOperator() && directives.getMaxValuesInInClause() > 0) {
final In<T> in = cb.in(jpaOperator.getLeft());
if (directives.getMaxValuesInInClause() < jpaOperator.getFixValues().size())
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NO_VALUES_OUT_OF_LIMIT,
HttpStatusCode.BAD_REQUEST, String.valueOf(directives.getMaxValuesInInClause()),
String.valueOf(jpaOperator.getFixValues().size()));
for (final JPAOperator value : jpaOperator.getFixValues()) {
in.value((T) value.get());
}
return in;
}
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR,
HttpStatusCode.BAD_REQUEST, jpaOperator.getName());
}
@SuppressWarnings("unchecked")
public Expression<?> convert(final JPAMethodCall jpaFunction) throws ODataApplicationException {
switch (jpaFunction.getFunction()) {
// First String functions
// TODO Escape like functions
case LENGTH:
return cb.length((Expression<String>) (jpaFunction.getParameter(0).get()));
case CONTAINS:
if (jpaFunction.getParameter(1) instanceof JPALiteralOperator) {
return cb.like((Expression<String>) (jpaFunction.getParameter(0).get()),
buildLikeLiteral(jpaFunction, "%", "%").toString());
} else {
return cb.like((Expression<String>) (jpaFunction.getParameter(0).get()),
(Expression<String>) ((JPAMethodCall) jpaFunction.getParameter(1)).get("%", "%"));
}
case ENDSWITH:
if (jpaFunction.getParameter(1) instanceof JPALiteralOperator) {
return cb.like((Expression<String>) (jpaFunction.getParameter(0).get()),
buildLikeLiteral(jpaFunction, "%", "").toString());
} else {
return cb.like((Expression<String>) (jpaFunction.getParameter(0).get()),
(Expression<String>) ((JPAMethodCall) jpaFunction.getParameter(1)).get("%", ""));
}
case STARTSWITH:
if (jpaFunction.getParameter(1) instanceof JPALiteralOperator) {
return cb.like((Expression<String>) (jpaFunction.getParameter(0).get()),
buildLikeLiteral(jpaFunction, "", "%").toString());
} else {
return cb.like((Expression<String>) (jpaFunction.getParameter(0).get()),
(Expression<String>) ((JPAMethodCall) jpaFunction.getParameter(1)).get("", "%"));
}
case INDEXOF:
final String searchString = ((String) ((JPALiteralOperator) jpaFunction.getParameter(1)).get());
return cb.locate((Expression<String>) (jpaFunction.getParameter(0).get()), searchString);
case SUBSTRING:
// OData defines start position in SUBSTRING as 0 (see
// http://docs.oasis-open.org/odata/odata/v4.0/os/part2-url-conventions/odata-v4.0-os-part2-url-conventions.html#_Toc372793820)
// SQL databases respectively use 1 as start position of a string
final Expression<Integer> start = convertLiteralToExpression(jpaFunction, 1, 1);
if (jpaFunction.noParameters() == 3) {
final Expression<Integer> length = convertLiteralToExpression(jpaFunction, 2, 0);
return cb.substring((Expression<String>) (jpaFunction.getParameter(0).get()), start, length);
} else {
return cb.substring((Expression<String>) (jpaFunction.getParameter(0).get()), start);
}
case TOLOWER:
// // TODO Locale!! and inverted parameter sequence
if (jpaFunction.getParameter(0).get() instanceof String)
return cb.literal(jpaFunction.getParameter(0).get().toString().toLowerCase());
return cb.lower((Expression<String>) (jpaFunction.getParameter(0).get()));
case TOUPPER:
if (jpaFunction.getParameter(0).get() instanceof String)
return cb.literal(jpaFunction.getParameter(0).get().toString().toUpperCase());
return cb.upper((Expression<String>) (jpaFunction.getParameter(0).get()));
case TRIM:
return cb.trim((Expression<String>) (jpaFunction.getParameter(0).get()));
case CONCAT:
if (jpaFunction.getParameter(0).get() instanceof final String parameter0)
return cb.concat(parameter0, (Expression<String>) (jpaFunction.getParameter(1).get()));
if (jpaFunction.getParameter(1).get() instanceof final String parameter1)
return cb.concat((Expression<String>) (jpaFunction.getParameter(0).get()), parameter1);
else
return cb.concat((Expression<String>) (jpaFunction.getParameter(0).get()),
(Expression<String>) (jpaFunction.getParameter(1).get()));
// Second Date-Time functions
case NOW:
return cb.currentTimestamp();
default:
return dbConverter.convert(jpaFunction);
}
}
private StringBuilder buildLikeLiteral(final JPAMethodCall jpaFunction, final String prefix,
final String postfix) throws ODataApplicationException {
final StringBuilder contains = new StringBuilder();
contains.append(prefix);
contains.append((String) ((JPALiteralOperator) jpaFunction.getParameter(1)).get());
contains.append(postfix);
return contains;
}
public final Expression<Boolean> convert(final JPAUnaryBooleanOperatorImp jpaOperator)
throws ODataApplicationException {
if (jpaOperator.getOperator() == UnaryOperatorKind.NOT)
return cb.not(jpaOperator.getLeft());
return dbConverter.convert(jpaOperator);
}
@SuppressWarnings({ "unchecked" })
private <Y extends Comparable<? super Y>> Expression<Boolean> comparisonExpression(
final BiFunction<Expression<? extends Y>, Expression<? extends Y>, Expression<Boolean>> allExpressionFunction,
final BiFunction<Expression<? extends Y>, Y, Expression<Boolean>> expressionObjectFunction,
final JPAComparisonOperator<? extends Y> jpaOperator) throws ODataApplicationException {
if (jpaOperator.getRight() instanceof JPAPrimitiveTypeOperator)
return expressionObjectFunction.apply(jpaOperator.getLeft(), (Y) jpaOperator.getRightAsComparable());
else
return allExpressionFunction.apply(jpaOperator.getLeft(), jpaOperator.getRightAsExpression());
}
@SuppressWarnings("unchecked")
private Expression<Integer> convertLiteralToExpression(final JPAMethodCall jpaFunction, final int parameterIndex,
final int offset) throws ODataApplicationException {
final JPAOperator parameter = jpaFunction.getParameter(parameterIndex);
if (parameter instanceof JPAArithmeticOperatorImp) {
if (offset != 0)
return cb.sum((Expression<Integer>) jpaFunction.getParameter(parameterIndex).get(), offset);
else
return (Expression<Integer>) jpaFunction.getParameter(parameterIndex).get();
} else {
return cb.literal(Integer.valueOf(parameter.get().toString()) + offset);
}
}
private Expression<Boolean> equalExpression(
final BiFunction<Expression<?>, Expression<?>, Expression<Boolean>> allExpressionFunction,
final BiFunction<Expression<?>, Object, Expression<Boolean>> expressionObjectFunction,
final Function<Expression<?>, Expression<Boolean>> nullFunction,
final JPAComparisonOperator<?> jpaOperator) throws ODataApplicationException {
if (jpaOperator.getRight() instanceof JPAPrimitiveTypeOperator) {
if (((JPAPrimitiveTypeOperator) jpaOperator.getRight()).isNull())
return nullFunction.apply(jpaOperator.getLeft());
else if (jpaOperator.getRight() instanceof JPAEnumerationOperator)
return expressionObjectFunction.apply(jpaOperator.getLeft(), ((JPAOperator) jpaOperator.getRight()).get());
else
return expressionObjectFunction.apply(jpaOperator.getLeft(), jpaOperator.getRightAsComparable());
} else {
return allExpressionFunction.apply(jpaOperator.getLeft(), jpaOperator.getRightAsExpression());
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterCrossComplier.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterCrossComplier.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractJoinQuery;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery;
/**
* Cross compiles Olingo generated AST of an OData filter into JPA criteria builder where condition.
*
* Details can be found:
* <ul>
* <li><a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301"
* >OData Version 4.0 Part 1 - 11.2.5.1 System Query Option $filter </a>
* <li><a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398094"
* >OData Version 4.0 Part 2 - 5.1.1 System Query Option $filter</a>
* <li><a href=
* "https://tools.oasis-open.org/version-control/browse/wsvn/odata/trunk/spec/ABNF/odata-abnf-construction-rules.txt">
* odata-abnf-construction-rules</a>
* </ul>
* @author Oliver Grande
*
*/
//TODO handle $it ...
public final class JPAFilterCrossComplier extends JPAAbstractFilter {
final JPAOperationConverter converter;
// TODO Check if it is allowed to select via navigation
// ...Organizations?$select=Roles/RoleCategory eq 'C'
// see also https://issues.apache.org/jira/browse/OLINGO-414
final EntityManager em;
final OData odata;
final JPAServiceDocument sd;
final List<UriResource> uriResourceParts;
final JPAAbstractQuery parent;
final Optional<JPAODataClaimProvider> claimsProvider;
final List<String> groups;
private From<?, ?> root;
private Optional<JPAFilterRestrictionsWatchDog> watchDog;
public JPAFilterCrossComplier(final OData odata, final JPAServiceDocument sd,
final JPAEntityType jpaEntityType, final JPAOperationConverter converter,
final JPAAbstractQuery parent, final From<?, ?> from, final JPAAssociationPath association,
final JPAODataRequestContextAccess requestContext) {
this(odata, sd, jpaEntityType, converter, parent, association, requestContext);
this.root = from;
}
public JPAFilterCrossComplier(final OData odata, final JPAServiceDocument sd,
final JPAEntityType jpaEntityType, final JPAOperationConverter converter, final JPAAbstractQuery parent,
final JPAAssociationPath association, final JPAODataRequestContextAccess requestContext) {
super(jpaEntityType, requestContext.getUriInfo(), association);
final Optional<JPAODataGroupProvider> groupsProvider = requestContext.getGroupsProvider();
this.uriResourceParts = requestContext.getUriInfo().getUriResourceParts();
this.converter = converter;
this.em = requestContext.getEntityManager();
this.odata = odata;
this.sd = sd;
this.parent = parent;
this.claimsProvider = requestContext.getClaimsProvider();
this.groups = groupsProvider.isPresent() ? groupsProvider.get().getGroups() : Collections.emptyList();
this.watchDog = Optional.empty();
}
public JPAFilterCrossComplier(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntityType,
final JPAOperationConverter converter, final JPAAbstractJoinQuery parent, final JPAAssociationPath association,
final JPAODataRequestContextAccess requestContext, final JPAFilterRestrictionsWatchDog watchDog) {
this(odata, sd, jpaEntityType, converter, parent, association, requestContext);
this.watchDog = Optional.ofNullable(watchDog);
}
public JPAFilterCrossComplier(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntityType,
final JPAOperationConverter converter, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final JPAODataRequestContextAccess requestContext,
final JPAFilterRestrictionsWatchDog watchDog) {
this(odata, sd, jpaEntityType, converter, parent, association, requestContext);
this.root = from;
this.watchDog = Optional.ofNullable(watchDog);
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFilterComplier#compile()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<Boolean> compile() throws ExpressionVisitException, ODataApplicationException {
try (JPARuntimeMeasurement measurement = parent.getDebugger().newMeasurement(this, "compile")) {
if (expression == null) {
return null;
}
final ExpressionVisitor<JPAOperator> visitor = new JPAVisitor(this);
return (Expression<Boolean>) expression.accept(visitor).get();
}
}
@Override
public Optional<JPAODataClaimProvider> getClaimsProvider() {
return claimsProvider;
}
@Override
public JPAOperationConverter getConverter() {
return converter;
}
@Override
public JPAServiceDebugger getDebugger() {
return parent.getDebugger();
}
@Override
public EntityManager getEntityManager() {
return em;
}
@Override
public JPAEntityType getJpaEntityType() {
return jpaEntityType;
}
@Override
public OData getOData() {
return odata;
}
@Override
public JPAAbstractQuery getParent() {
return parent;
}
@SuppressWarnings("unchecked")
@Override
public <S, T> From<S, T> getRoot() {
if (root == null)
return (From<S, T>) parent.getRoot();
return (From<S, T>) root;
}
@Override
public JPAServiceDocument getSd() {
return sd;
}
@Override
public List<UriResource> getUriResourceParts() {
return uriResourceParts;
}
@Override
public List<String> getGroups() {
return groups;
}
@Override
public Optional<JPAFilterRestrictionsWatchDog> getWatchDog() {
return watchDog;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAComparisonOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAComparisonOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
public interface JPAComparisonOperator<T extends Comparable<T>> extends JPAExpressionOperator {
Expression<T> getLeft() throws ODataApplicationException;
Object getRight();
Comparable<T> getRightAsComparable() throws ODataApplicationException;
Expression<T> getRightAsExpression() throws ODataApplicationException;
@SuppressWarnings("unchecked")
@Override
BinaryOperatorKind getOperator();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAJavaFunctionOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAJavaFunctionOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import com.sap.olingo.jpa.metadata.api.JPAODataQueryContext;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.processor.JPAJavaFunctionProcessor;
/**
* Handle OData Functions that are implemented as user defined data base functions. This will be mapped
* to JPA criteria builder function().
*
* @author Oliver Grande
*
*/
public final class JPAJavaFunctionOperator implements JPAExpression {
private final JPAJavaFunction jpaFunction;
private final UriResourceFunction resource;
private final JPAODataQueryContext queryContext;
private final JPAServiceDocument sd;
public JPAJavaFunctionOperator(final JPAVisitor jpaVisitor, final UriResourceFunction resource,
final JPAJavaFunction jpaFunction) {
super();
this.queryContext = new ODataJPAQueryContext(jpaVisitor);
this.sd = jpaVisitor.getSd();
this.resource = resource;
this.jpaFunction = jpaFunction;
}
@SuppressWarnings("unchecked")
@Override
public Expression<Boolean> get() throws ODataApplicationException {
return (Expression<Boolean>) new JPAJavaFunctionProcessor(sd, resource, jpaFunction, queryContext).process();
}
@Override
public String getName() {
return jpaFunction.getExternalName();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPADBFunctionOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPADBFunctionOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_FILTER;
import java.util.List;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPATypeConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
/**
* Handle OData Functions that are implemented as user defined data base functions. This will be mapped
* to JPA criteria builder function().
*
* @author Oliver Grande
*
*/
final class JPADBFunctionOperator implements JPAOperator {
private final JPADataBaseFunction jpaFunction;
private final JPAVisitor visitor;
private final List<UriParameter> uriParams;
public JPADBFunctionOperator(final JPAVisitor jpaVisitor, final List<UriParameter> uriParams,
final JPADataBaseFunction jpaFunction) {
super();
this.uriParams = uriParams;
this.visitor = jpaVisitor;
this.jpaFunction = jpaFunction;
}
@Override
public Expression<?> get() throws ODataApplicationException {
if (jpaFunction.getResultParameter().isCollection()) {
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_FUNCTION_COLLECTION,
HttpStatusCode.NOT_IMPLEMENTED);
}
if (!JPATypeConverter.isScalarType(
jpaFunction.getResultParameter().getType())) {
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_FUNCTION_NOT_SCALAR,
HttpStatusCode.NOT_IMPLEMENTED);
}
final CriteriaBuilder cb = visitor.getCriteriaBuilder();
List<JPAParameter> parameters;
try {
parameters = jpaFunction.getParameter();
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
final Expression<?>[] jpaParameter = new Expression<?>[parameters.size()];
for (int i = 0; i < parameters.size(); i++) {
// a. $it/Area b. Area c. 10000
final UriParameter p = findUriParameter(parameters.get(i));
if (p != null && p.getText() != null) {
final JPALiteralOperator operator = new JPALiteralOperator(visitor.getOData(), new ParameterLiteral(p
.getText()));
jpaParameter[i] = cb.literal(operator.get(parameters.get(i)));
} else if (p != null && p.getExpression() != null) {
try {
jpaParameter[i] = (Expression<?>) p.getExpression().accept(visitor).get();
} catch (final ExpressionVisitException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.NOT_IMPLEMENTED);
}
} else {
throw new ODataJPAFilterException(NOT_SUPPORTED_FILTER, HttpStatusCode.NOT_IMPLEMENTED);
}
}
return cb.function(jpaFunction.getDBName(), jpaFunction.getResultParameter().getType(), jpaParameter);
}
private UriParameter findUriParameter(final JPAParameter jpaFunctionParam) {
for (final UriParameter uriParam : uriParams) {
if (uriParam.getName().equals(jpaFunctionParam.getName())) {
return uriParam;
}
}
return null;
}
public JPAOperationResultParameter getReturnType() {
return jpaFunction.getResultParameter();
}
@Override
public String getName() {
return jpaFunction.getDBName();
}
private record ParameterLiteral(String text) implements Literal {
@Override
public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
public String getText() {
return text;
}
@Override
public EdmType getType() {
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAVisitableExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAVisitableExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
public interface JPAVisitableExpression extends VisitableExpression {
public UriInfoResource getMember();
public Literal getLiteral();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAExistsOperation.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAExistsOperation.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceLambdaVariable;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery;
import com.sap.olingo.jpa.processor.core.query.JPANavigationPropertyInfo;
import com.sap.olingo.jpa.processor.core.query.Utility;
abstract class JPAExistsOperation implements JPAExpressionOperator {
protected final JPAOperationConverter converter;
protected final List<UriResource> uriResourceParts;
protected final JPAAbstractQuery root;
protected final JPAServiceDocument sd;
protected final EntityManager em;
protected final OData odata;
protected final From<?, ?> from;
protected final Optional<JPAODataClaimProvider> claimsProvider;
protected final List<String> groups;
JPAExistsOperation(final JPAFilterComplierAccess jpaComplier) {
this.uriResourceParts = jpaComplier.getUriResourceParts();
this.root = jpaComplier.getParent();
this.sd = jpaComplier.getSd();
this.em = jpaComplier.getEntityManager();
this.converter = jpaComplier.getConverter();
this.odata = jpaComplier.getOData();
this.from = jpaComplier.getRoot();
this.claimsProvider = jpaComplier.getClaimsProvider();
this.groups = jpaComplier.getGroups();
}
@Override
public Expression<Boolean> get() throws ODataApplicationException {
try {
return converter.cb.exists(getExistsQuery().query());
} catch (final ODataJPAIllegalAccessException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
abstract SubQueryItem getExistsQuery() throws ODataApplicationException, ODataJPAIllegalAccessException;
protected List<JPANavigationPropertyInfo> determineAssociations(final JPAServiceDocument sd,
final List<UriResource> resourceParts) throws ODataApplicationException {
final List<JPANavigationPropertyInfo> pathList = new ArrayList<>();
StringBuilder associationName = null;
UriResourcePartTyped navigation = null;
if (Utility.hasNavigation(resourceParts) || Utility.hasCollection(resourceParts)) {
for (int i = resourceParts.size() - 1; i >= 0; i--) {
final UriResource resourcePart = resourceParts.get(i);
if (resourcePart instanceof final UriResourceNavigation nextNavigation) {
if (navigation != null)
pathList.add(new JPANavigationPropertyInfo(sd, navigation, Utility.determineAssociationPath(sd,
nextNavigation, associationName), null));
navigation = nextNavigation;
associationName = new StringBuilder();
associationName.insert(0, nextNavigation.getProperty().getName());
}
if (navigation != null) {
if (resourceParts.get(i) instanceof final UriResourceComplexProperty complexProperty) {
associationName.insert(0, JPAPath.PATH_SEPARATOR);
associationName.insert(0, complexProperty.getProperty().getName());
} else if (resourcePart instanceof final UriResourceEntitySet entitySet)
pathList.add(new JPANavigationPropertyInfo(sd, navigation, Utility.determineAssociationPath(sd,
entitySet, associationName), null));
else if (resourcePart instanceof final UriResourceLambdaVariable lambdaVariable)
pathList.add(new JPANavigationPropertyInfo(sd, navigation, Utility.determineAssociation(sd,
lambdaVariable.getType(), associationName), null));
}
if (Utility.isCollection(resourcePart)) {
navigation = (UriResourcePartTyped) resourcePart;
associationName = new StringBuilder();
associationName.insert(0, ((UriResourceProperty) navigation).getProperty().getName());
}
}
}
return pathList;
}
protected record SubQueryItem(List<Path<Comparable<?>>> jpaPath, Subquery<List<Comparable<?>>> query) {}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAPrimitiveTypeOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAPrimitiveTypeOperator.java | package com.sap.olingo.jpa.processor.core.filter;
public interface JPAPrimitiveTypeOperator extends JPAOperator {
public boolean isNull();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterComplier.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterComplier.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
public interface JPAFilterComplier {
Expression<Boolean> compile() throws ExpressionVisitException, ODataApplicationException;
/**
* Returns a list of all filter elements of type Member. This could be used e.g. to determine if a join is required
* @throws ODataApplicationException
*/
List<JPAPath> getMember() throws ODataApplicationException;
Optional<JPAFilterRestrictionsWatchDog> getWatchDog();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
public interface JPAExpression extends JPAOperator {
@Override
Expression<Boolean> get() throws ODataApplicationException;
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAInvertibleVisitableExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAInvertibleVisitableExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
/**
*
* @author Oliver Grande
* @since 1.1.1
* 01.08.2023
*/
public abstract class JPAInvertibleVisitableExpression implements JPAVisitableExpression {
// Indicates that the expression has inverted the operand e.g. from EQ to NE. client may need to adjust e.g. perform
// NOT EXISTS instead of EXISTS
private boolean inversionRequired;
protected final Literal literal;
protected final BinaryOperatorKind operator;
protected final Member member;
protected JPAInvertibleVisitableExpression(final Literal literal, final BinaryOperatorKind operator,
final Member member) throws ODataJPAFilterException {
super();
this.literal = literal;
this.operator = determineOperator(operator, literal);
this.member = member;
}
@Override
public UriInfoResource getMember() {
return member.getResourcePath();
}
@Override
public Literal getLiteral() {
return literal;
}
/**
* Expression has performed an inversion of the operator. A client has to reaction on this, e.g. by using NOT EXISTS
* instead of EXISTS.
*/
public boolean isInversionRequired() {
return inversionRequired;
}
/**
* Client has performed an inversion, usually from EXISTS to NOT EXISTS. No need for others to do that as well
*/
public void inversionPerformed() {
inversionRequired = false;
}
protected abstract BinaryOperatorKind determineOperator(final BinaryOperatorKind operator, final Literal literal)
throws ODataJPAFilterException;
void setInversionRequired(final boolean inversionRequired) {
this.inversionRequired = inversionRequired;
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAArithmeticOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAArithmeticOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
public interface JPAArithmeticOperator extends JPAOperator {
@Override
Expression<Number> get() throws ODataApplicationException;
BinaryOperatorKind getOperator();
Object getRight();
Expression<Number> getLeft(CriteriaBuilder cb) throws ODataApplicationException;
Number getRightAsNumber(CriteriaBuilder cb) throws ODataApplicationException;
Expression<Number> getRightAsExpression() throws ODataApplicationException;
Expression<Integer> getLeftAsIntExpression() throws ODataApplicationException;
Expression<Integer> getRightAsIntExpression() throws ODataApplicationException;
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPALambdaAllOperation.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPALambdaAllOperation.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.Unary;
import org.apache.olingo.server.api.uri.queryoption.expression.UnaryOperatorKind;
final class JPALambdaAllOperation extends JPALambdaOperation {
JPALambdaAllOperation(final JPAFilterComplierAccess jpaComplier, final Member member) {
super(jpaComplier, member);
}
public Subquery<?> getNotExistsQuery() throws ODataApplicationException {
return getSubQuery(new NotExpression(determineExpression()));
}
@Override
public Expression<Boolean> get() throws ODataApplicationException {
final CriteriaBuilder cb = converter.cb;
return cb.and(cb.exists(getExistsQuery().query()), cb.not(cb.exists(getNotExistsQuery())));
}
@Override
public String getName() {
return "ALL";
}
@SuppressWarnings("unchecked")
@Override
public Enum<?> getOperator() {
return null;
}
private class NotExpression implements Unary {
private final org.apache.olingo.server.api.uri.queryoption.expression.Expression expression;
public NotExpression(final org.apache.olingo.server.api.uri.queryoption.expression.Expression expression) {
super();
this.expression = expression;
}
@Override
public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
final T operand = expression.accept(visitor);
return visitor.visitUnaryOperator(getOperator(), operand);
}
@Override
public org.apache.olingo.server.api.uri.queryoption.expression.Expression getOperand() {
return expression;
}
@Override
public UnaryOperatorKind getOperator() {
return UnaryOperatorKind.NOT;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
public final class JPAFilterExpression implements JPAVisitableExpression {
private final Literal literal;
private final BinaryOperatorKind operator;
private final Member member;
private final List<Literal> literals;
public JPAFilterExpression(final Member member, final Literal literal, final BinaryOperatorKind operator) {
super();
this.literal = literal;
this.operator = operator;
this.member = member;
this.literals = List.of();
}
public JPAFilterExpression(final Member member, final List<Literal> literals, final BinaryOperatorKind operator) {
super();
this.literal = null;
this.operator = operator;
this.member = member;
this.literals = literals;
}
@Override
public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
final T left = visitor.visitMember(member);
if (literal != null) {
final T right = visitor.visitLiteral(literal);
return visitor.visitBinaryOperator(operator, left, right);
} else {
final List<T> right = new ArrayList<>(literals.size());
for (final Literal l : literals)
right.add(visitor.visitLiteral(l));
return visitor.visitBinaryOperator(operator, left, right);
}
}
// @Override
// public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
// T localLeft = this.left.accept(visitor);
// if (this.right != null) {
// T localRight = this.right.accept(visitor);
// return visitor.visitBinaryOperator(operator, localLeft, localRight);
// } else if (this.expressions != null) {
// List<T> expressions = new ArrayList<>();
// for (final Expression expression : this.expressions) {
// expressions.add(expression.accept(visitor));
// }
// return visitor.visitBinaryOperator(operator, localLeft, expressions);
// }
// return null;
// }
@Override
public UriInfoResource getMember() {
return member.getResourcePath();
}
@Override
public Literal getLiteral() {
return literal;
}
@Override
public String toString() {
return "JPAFilterExpression [literal=" + literal
+ ", operator=" + operator + ", member="
+ "[resourcePath="
+ member.getResourcePath().getUriResourceParts()
+ ", startTypeFilter= " + member.getStartTypeFilter()
+ ", type= " + member.getType()
+ "]]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterAggregationType.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterAggregationType.java | package com.sap.olingo.jpa.processor.core.filter;
public enum JPAFilterAggregationType {
COUNT;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAEnumerationOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAEnumerationOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEnumerationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
public final class JPAEnumerationOperator implements JPAEnumerationBasedOperator {
private final JPAEnumerationAttribute jpaAttribute;
private final List<String> value;
JPAEnumerationOperator(JPAEnumerationAttribute jpaEnumerationAttribute, List<String> enumValues) {
super();
this.jpaAttribute = jpaEnumerationAttribute;
this.value = enumValues;
}
/**
* Returns either an instance of an enumeration or an array of enumerations. This is sufficient for <i>eq</i>,
* <i>ne</i> and <i>has</i> operations, but will not work with any operation that requires a <code>comparable</code>
* like <i>gt</i>. As of now such operations are already blocked by Olingo in ExpressionParser.checkType().<br>
* In case in the future these operations shall be supported this method has to return an array of
* <code>comparable</code>, which goes with an incompatible change of annotation EdmEnumeration, as converters are
* required using such an array.
*/
@Override
public Object get() throws ODataApplicationException {
try {
return jpaAttribute.convert(value);
} catch (ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
@Override
public boolean isNull() {
return value == null;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAEnumerationBasedOperator#getValue()
*/
@Override
public Number getValue() throws ODataJPAFilterException {
try {
return jpaAttribute.valueOf(value);
} catch (ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
@Override
public String getName() {
return "";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterRestrictionsWatchDog.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterRestrictionsWatchDog.java | package com.sap.olingo.jpa.processor.core.filter;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException.MessageKeys.FILTERING_MISSING_PROPERTIES;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException.MessageKeys.FILTERING_NOT_SUPPORTED;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException.MessageKeys.FILTERING_REQUIRED;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlDynamicExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyPath;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.helper.AbstractWatchDog;
/**
* In case an annotatable artifact has been annotated with Capabilities#FilterRestrictions, it is checked that the
* generated WHERE clause fulfills the specified restrictions. See:
* <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.md#FilterRestrictionsType"><i>FilterRestrictionsType</i></a>
*
* @author Oliver Grande
* @since 1.1.1
* 08.05.2023
*/
public class JPAFilterRestrictionsWatchDog extends AbstractWatchDog {
static final String REQUIRED_PROPERTIES = "RequiredProperties";
static final String FILTERABLE = "Filterable";
static final String REQUIRES_FILTER = "RequiresFilter";
static final String VOCABULARY_ALIAS = "Capabilities";
static final String TERM = "FilterRestrictions";
private final Optional<CsdlAnnotation> annotation;
private final Map<String, CsdlExpression> properties;
private final String externalName;
private final Set<String> requiredPropertyPath;
private boolean singleEntityRequested;
public JPAFilterRestrictionsWatchDog(final JPAAnnotatable annotatable, final boolean singleEntityRequested)
throws ODataJPAQueryException {
try {
if (annotatable != null) {
externalName = annotatable.getExternalName();
annotation = Optional.ofNullable(annotatable.getAnnotation(VOCABULARY_ALIAS, TERM));
properties = determineProperties();
requiredPropertyPath = extractRequiredPropertyPath(properties.get(REQUIRED_PROPERTIES));
} else {
externalName = "";
annotation = Optional.empty();
properties = Collections.emptyMap();
requiredPropertyPath = Collections.emptySet();
}
this.singleEntityRequested = singleEntityRequested;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
public void watch(final Expression<Boolean> filter) throws ODataJPAFilterException {
watchFilterable(filter);
watchRequiresFilter(filter);
watchRequiredProperties();
}
public void watch(final JPAPath attributePath) {
if (attributePath != null)
requiredPropertyPath.remove(attributePath.getAlias());
}
Set<String> getRequiredPropertyPath() {
return Collections.unmodifiableSet(requiredPropertyPath);
}
private Map<String, CsdlExpression> determineProperties() {
if (annotation.isPresent()) {
return getAnnotationProperties(annotation);
} else
return Collections.emptyMap();
}
private Set<String> extractRequiredPropertyPath(final CsdlExpression expression) {
if (expression != null)
return expression.asDynamic().asCollection().getItems().stream()
.map(CsdlExpression::asDynamic)
.map(CsdlDynamicExpression::asPropertyPath)
.map(CsdlPropertyPath::getValue)
.collect(Collectors.toSet());
else
return Collections.emptySet();
}
private boolean filteringIsAllowed() {
final CsdlExpression filterable = properties.get(FILTERABLE);
return filterable == null
|| (Boolean.valueOf(filterable.asConstant().getValue()));
}
private boolean filterIsRequired() {
final CsdlExpression requiresFilter = properties.get(REQUIRES_FILTER);
return requiresFilter != null
&& Boolean.valueOf(requiresFilter.asConstant().getValue())
&& !singleEntityRequested;
}
private void watchFilterable(final Expression<Boolean> filter) throws ODataJPAFilterException {
if (!filteringIsAllowed()
&& filter != null)
throw new ODataJPAFilterException(FILTERING_NOT_SUPPORTED, HttpStatusCode.BAD_REQUEST,
externalName);
}
private void watchRequiredProperties() throws ODataJPAFilterException {
if (filterIsRequired()
&& !requiredPropertyPath.isEmpty()) {
final String missingProperties = requiredPropertyPath.stream()
.collect(Collectors.joining(" ,"));
// Filter not found for required properties '%1$s' at '%2$s'
throw new ODataJPAFilterException(FILTERING_MISSING_PROPERTIES, HttpStatusCode.BAD_REQUEST,
missingProperties, externalName);
}
}
private void watchRequiresFilter(final Expression<Boolean> filter) throws ODataJPAFilterException {
if (filterIsRequired()
&& filter == null)
throw new ODataJPAFilterException(FILTERING_REQUIRED, HttpStatusCode.BAD_REQUEST,
externalName);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPALambdaAnyOperation.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPALambdaAnyOperation.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
final class JPALambdaAnyOperation extends JPALambdaOperation implements JPAExpressionOperator {
JPALambdaAnyOperation(final JPAFilterComplierAccess jpaComplier, final Member member) {
super(jpaComplier, member);
}
@SuppressWarnings("unchecked")
@Override
public Enum<?> getOperator() {
return null;
}
@Override
public String getName() {
return "ANY";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/ODataJPAQueryContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/ODataJPAQueryContext.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import com.sap.olingo.jpa.metadata.api.JPAODataQueryContext;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
public class ODataJPAQueryContext implements JPAODataQueryContext {
private final From<?, ?> from;
private final CriteriaBuilder cb;
private final JPAEntityType et;
public ODataJPAQueryContext(final JPAVisitor visitor) {
this.from = visitor.getRoot();
this.cb = visitor.getCriteriaBuilder();
this.et = visitor.getEntityType();
}
@Override
@SuppressWarnings("unchecked")
public <X, Y> From<X, Y> getFrom() {
return (From<X, Y>) from;
}
@Override
public JPAEntityType getEntityType() {
return et;
}
@Override
public CriteriaBuilder getCriteriaBuilder() {
return cb;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAComparisonOperatorImp.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAComparisonOperatorImp.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
//
public class JPAComparisonOperatorImp<T extends Comparable<T>> implements JPAComparisonOperator<T> {
private final JPAOperationConverter converter;
private final BinaryOperatorKind operator;
private final JPAOperator left;
private final JPAOperator right;
public JPAComparisonOperatorImp(final JPAOperationConverter converter, final BinaryOperatorKind operator,
final JPAOperator left, final JPAOperator right) {
super();
this.converter = converter;
this.operator = operator;
this.left = left;
this.right = right;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator#get()
*/
@Override
public Expression<Boolean> get() throws ODataApplicationException {
return converter.convert(this);
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator#getOperator()
*/
@SuppressWarnings("unchecked")
@Override
public BinaryOperatorKind getOperator() {
return operator;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator#getLeft()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<T> getLeft() throws ODataApplicationException {
if (left instanceof JPALiteralOperator)
return (Expression<T>) right.get();
return (Expression<T>) left.get();
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator#getRight()
*/
@Override
public Object getRight() {
if (left instanceof JPALiteralOperator)
return left;
return right;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator#getRightAsComparable()
*/
@Override
@SuppressWarnings("unchecked")
public Comparable<T> getRightAsComparable() throws ODataApplicationException {
if (left instanceof JPALiteralOperator) {
if (right instanceof JPAMemberOperator)
return (Comparable<T>) ((JPALiteralOperator) left).get(((JPAMemberOperator) right).determineAttribute());
else
return (Comparable<T>) left.get();
}
if (right instanceof JPALiteralOperator) {
if (left instanceof JPAMemberOperator)
return (Comparable<T>) ((JPALiteralOperator) right).get(((JPAMemberOperator) left).determineAttribute());
else {
return (Comparable<T>) right.get();
}
}
return (Comparable<T>) right.get();
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator#getRightAsExpression()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<T> getRightAsExpression() throws ODataApplicationException {
return (Expression<T>) right.get();
}
@Override
public String getName() {
return operator.name();
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterComplierAccess.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterComplierAccess.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.From;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriResource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery;
interface JPAFilterComplierAccess {
/**
* @return Query a filter belongs to.
*/
JPAAbstractQuery getParent();
List<UriResource> getUriResourceParts();
JPAServiceDocument getSd();
OData getOData();
EntityManager getEntityManager();
JPAEntityType getJpaEntityType();
JPAOperationConverter getConverter();
/**
* Root of the query the filter belongs to.
* @param <S>
* @param <T>
* @return
*/
<S, T> From<S, T> getRoot();
JPAServiceDebugger getDebugger();
JPAAssociationPath getAssociation();
Optional<JPAODataClaimProvider> getClaimsProvider();
List<String> getGroups();
Optional<JPAFilterRestrictionsWatchDog> getWatchDog();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAExpressionVisitor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAExpressionVisitor.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.From;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
public interface JPAExpressionVisitor extends ExpressionVisitor<JPAOperator> {
public OData getOData();
public From<?, ?> getRoot();
public JPAEntityType getEntityType();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAUnaryBooleanOperatorImp.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAUnaryBooleanOperatorImp.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.UnaryOperatorKind;
final class JPAUnaryBooleanOperatorImp implements JPAUnaryBooleanOperator {
private final JPAOperationConverter converter;
private final UnaryOperatorKind operator;
private final JPAExpression left;
public JPAUnaryBooleanOperatorImp(final JPAOperationConverter converter, final UnaryOperatorKind operator,
final JPAExpression left) {
super();
this.converter = converter;
this.operator = operator;
this.left = left;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAUnaryBooleanOperator#get()
*/
@Override
public Expression<Boolean> get() throws ODataApplicationException {
return converter.convert(this);
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAUnaryBooleanOperator#getLeft()
*/
@Override
public Expression<Boolean> getLeft() throws ODataApplicationException {
return left.get();
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAUnaryBooleanOperator#getOperator()
*/
@Override
public UnaryOperatorKind getOperator() {
return operator;
}
@Override
public String getName() {
return operator.name();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPANavigationOperation.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPANavigationOperation.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
/**
* In case the query result shall be filtered on an attribute of navigation target a sub-select will be generated.
* <p>
* E.g.<br>
* <ul>
* <li>Organizations?$select=ID&$filter=Roles/$count eq 2</li>
* <li>CollectionDeeps?$filter=FirstLevel/SecondLevel/Comment/$count eq 2&$select=ID</li>
* <li>Organizations?$filter=AdministrativeInformation/Created/User/LastName eq 'Mustermann'</li>
* <li>AdministrativeDivisions?$filter=Parent/Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE212'</li>
* <li>AssociationOneToOneSources?$filter=ColumnTarget eq null</li>
* </ul>
* @author Oliver Grande
*
*/
final class JPANavigationOperation extends JPAAbstractNavigationOperation {
final JPALiteralOperator operand;
private static final OperatorPair determineOperatorsLeftRight(final JPAOperator left, final JPAOperator right) {
if (left instanceof final JPAMemberOperator memberOperator)
return new OperatorPair((JPALiteralOperator) right, memberOperator);
else
return new OperatorPair((JPALiteralOperator) left, (JPAMemberOperator) right);
}
private static final JPAMemberOperator determineOperatorsByParameters(final List<JPAOperator> parameters) {
if (parameters.get(0) instanceof final JPAMemberOperator memberOperator)
return memberOperator;
else
return (JPAMemberOperator) parameters.get(1);
}
public JPANavigationOperation(final BinaryOperatorKind operator,
final JPANavigationOperation jpaNavigationOperation, final JPALiteralOperator operand,
final JPAFilterComplierAccess jpaComplier) {
super(jpaComplier, jpaNavigationOperation.methodCall, operator, jpaNavigationOperation.jpaMember);
this.operand = operand;
}
JPANavigationOperation(final JPAFilterComplierAccess jpaComplier, final BinaryOperatorKind operator,
final JPAOperator left, final JPAOperator right) {
super(jpaComplier, null, operator, determineOperatorsLeftRight(left, right).member);
this.operand = determineOperatorsLeftRight(left, right).literal;
}
public JPANavigationOperation(final JPAFilterComplierAccess jpaComplier, final MethodKind methodCall,
final List<JPAOperator> parameters) {
super(jpaComplier, methodCall, null, determineOperatorsByParameters(parameters));
if (parameters.get(0) instanceof JPAMemberOperator) {
operand = parameters.size() > 1 ? (JPALiteralOperator) parameters.get(1) : null;
} else {
operand = (JPALiteralOperator) parameters.get(0);
}
}
@SuppressWarnings("unchecked")
@Override
public Enum<?> getOperator() {
return null;
}
@Override
VisitableExpression createExpression() throws ODataJPAFilterException {
if (operator != null && methodCall == null) {
final List<UriResource> parts = jpaMember.getMember().getResourcePath().getUriResourceParts();
if (UriResourceKind.count == parts.get(parts.size() - 1).getKind())
return new JPACountExpression(getMember(), operand.getLiteral(),
operator);
if ("null".equals(operand.getLiteral().getText()))
return new JPANullExpression(getMember(), operand.getLiteral(),
operator);
return new JPAFilterExpression(getMember(), operand.getLiteral(),
operator);
}
if (operator == null && methodCall != null) {
return new JPAMethodExpression(getMember(), operand, this.methodCall);
} else {
final JPAVisitableExpression methodExpression = new JPAMethodExpression(getMember(), operand, this.methodCall);
return new JPABinaryExpression(methodExpression, operand.getLiteral(), operator);
}
}
@Override
public String toString() {
return "JPANavigationOperation [operator=" + operator + ", jpaMember=" + jpaMember + ", operand=" + operand
+ ", methodCall=" + methodCall + "]";
}
private static record OperatorPair(JPALiteralOperator literal, JPAMemberOperator member) {
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterElementComplier.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAFilterElementComplier.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery;
/**
* Compiles just one Expression. Mainly build for filter on navigation
* @author Oliver Grande
*
*/
//TODO handle $it ...
public final class JPAFilterElementComplier extends JPAAbstractFilter {
final JPAOperationConverter converter;
final EntityManager em;
final OData odata;
final JPAServiceDocument sd;
final List<UriResource> uriResourceParts;
final JPAAbstractQuery parent;
final List<String> groups;
/**
*
* @param odata
* @param sd
* @param em
* @param jpaEntityType
* @param converter
* @param uriResourceParts
* @param parent: Query a filter belongs to.
* @param expression
* @param association
* @param groups
*/
public JPAFilterElementComplier(final OData odata, final JPAServiceDocument sd, final EntityManager em,
final JPAEntityType jpaEntityType, final JPAOperationConverter converter,
final List<UriResource> uriResourceParts, final JPAAbstractQuery parent, final VisitableExpression expression,
final JPAAssociationPath association, final List<String> groups) {
super(jpaEntityType, expression, association);
this.converter = converter;
this.em = em;
this.odata = odata;
this.sd = sd;
this.uriResourceParts = uriResourceParts;
this.parent = parent;
this.groups = groups;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFilterComplier#compile()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<Boolean> compile() throws ExpressionVisitException, ODataApplicationException {
try (JPARuntimeMeasurement measurement = parent.getDebugger().newMeasurement(this, "compile")) {
final ExpressionVisitor<JPAOperator> visitor = new JPAVisitor(this);
return (Expression<Boolean>) expression.accept(visitor).get();
}
}
@Override
public JPAOperationConverter getConverter() {
return converter;
}
@Override
public JPAEntityType getJpaEntityType() {
return jpaEntityType;
}
@Override
public EntityManager getEntityManager() {
return em;
}
@Override
public OData getOData() {
return odata;
}
@Override
public JPAServiceDocument getSd() {
return sd;
}
@Override
public List<UriResource> getUriResourceParts() {
return uriResourceParts;
}
@Override
public JPAAbstractQuery getParent() {
return parent;
}
public VisitableExpression getExpressionMember() {
return expression;
}
@SuppressWarnings("unchecked")
@Override
public <S, T> From<S, T> getRoot() {
return (From<S, T>) parent.getRoot();
}
@Override
public JPAServiceDebugger getDebugger() {
return parent.getDebugger();
}
@Override
public Optional<JPAODataClaimProvider> getClaimsProvider() {
return Optional.empty();
}
@Override
public List<String> getGroups() {
return groups;
}
@Override
public Optional<JPAFilterRestrictionsWatchDog> getWatchDog() {
return Optional.empty();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPANullExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPANullExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
/**
* Expression for filter on navigation is null. E.g.:<br>
* $filter=navigation eq null
* @author Oliver Grande
* @since 1.1.1
* 01.08.2023
*/
public class JPANullExpression extends JPAInvertibleVisitableExpression {
public JPANullExpression(final Member member, final Literal literal, final BinaryOperatorKind operator)
throws ODataJPAFilterException {
super(literal, operator, member);
}
@Override
public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
return null;
}
@Override
protected BinaryOperatorKind determineOperator(final BinaryOperatorKind operator, final Literal literal)
throws ODataJPAFilterException {
if (operator == BinaryOperatorKind.EQ)
setInversionRequired(true);
return operator;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPABooleanOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPABooleanOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
public interface JPABooleanOperator extends JPAExpressionOperator {
Expression<Boolean> getLeft() throws ODataApplicationException;
Expression<Boolean> getRight() throws ODataApplicationException;
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAArithmeticOperatorImp.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAArithmeticOperatorImp.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
class JPAArithmeticOperatorImp implements JPAArithmeticOperator {
private final JPAOperationConverter converter;
private final BinaryOperatorKind operator;
private final JPAOperator left;
private final JPAOperator right;
public JPAArithmeticOperatorImp(final JPAOperationConverter converter, final BinaryOperatorKind operator,
final JPAOperator left, final JPAOperator right) {
super();
this.converter = converter;
this.operator = operator;
this.left = left;
this.right = right;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#get()
*/
@Override
public Expression<Number> get() throws ODataApplicationException {
return converter.convert(this);
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getOperator()
*/
@Override
public BinaryOperatorKind getOperator() {
return operator;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getRight()
*/
@Override
public Object getRight() {
if (left instanceof JPALiteralOperator)
return left;
return right;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getLeft(jakarta.persistence.criteria.
* CriteriaBuilder)
*/
@Override
@SuppressWarnings("unchecked")
public Expression<Number> getLeft(final CriteriaBuilder cb) throws ODataApplicationException {
if (left instanceof JPALiteralOperator) {
if (right instanceof JPALiteralOperator)
return cb.literal((Number) left.get());
else
return (Expression<Number>) right.get();
}
return (Expression<Number>) left.get();
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getRightAsNumber(javax.persistence.criteria.
* CriteriaBuilder)
*/
@Override
public Number getRightAsNumber(final CriteriaBuilder cb) throws ODataApplicationException {
// Determine attribute in order to determine type of literal attribute and correctly convert it
if (left instanceof JPALiteralOperator) {
if (right instanceof JPALiteralOperator)
return (Number) right.get();
else if (right instanceof JPAMemberOperator)
return (Number) ((JPALiteralOperator) left).get(((JPAMemberOperator) right).determineAttribute());
else
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR_TYPE,
HttpStatusCode.NOT_IMPLEMENTED);
} else if (left instanceof JPAMemberOperator) {
if (right instanceof JPALiteralOperator)
return (Number) ((JPALiteralOperator) right).get(((JPAMemberOperator) left).determineAttribute());
else
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR_TYPE,
HttpStatusCode.NOT_IMPLEMENTED);
} else if (left instanceof JPADBFunctionOperator) {
if (right instanceof JPALiteralOperator)
return (Number) ((JPALiteralOperator) right).get(((JPADBFunctionOperator) left).getReturnType());
else
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR_TYPE,
HttpStatusCode.NOT_IMPLEMENTED);
} else {
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR_TYPE,
HttpStatusCode.NOT_IMPLEMENTED);
}
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getRightAsExpression()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<Number> getRightAsExpression() throws ODataApplicationException {
return (Expression<Number>) ((JPAMemberOperator) right).get();
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getLeftAsIntExpression()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<Integer> getLeftAsIntExpression() throws ODataApplicationException {
if (left instanceof JPALiteralOperator)
return (Expression<Integer>) right.get();
return (Expression<Integer>) left.get();
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator#getRightAsIntExpression()
*/
@Override
@SuppressWarnings("unchecked")
public Expression<Integer> getRightAsIntExpression() throws ODataApplicationException {
return (Expression<Integer>) ((JPAMemberOperator) right).get();
}
@Override
public String getName() {
return operator.name();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodCallImp.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAMethodCallImp.java | package com.sap.olingo.jpa.processor.core.filter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.MethodKind;
class JPAMethodCallImp implements JPAMethodCall {
private final MethodKind methodCall;
private final List<JPAOperator> parameters;
private final JPAOperationConverter converter;
public JPAMethodCallImp(final JPAOperationConverter converter, final MethodKind methodCall,
final List<JPAOperator> parameters) {
super();
this.methodCall = methodCall;
this.parameters = parameters;
this.converter = converter;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFunctionCall#get()
*/
@Override
public Object get() throws ODataApplicationException {
return converter.convert(this);
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFunctionCall#get(String prefix, String suffix)
*/
@Override
public Object get(final String prefix, final String suffix) throws ODataApplicationException {
final List<JPAOperator> paramCopy = new ArrayList<>(parameters);
if (!parameters.isEmpty() && parameters.get(0) instanceof final JPALiteralOperator literalOperator) {
parameters.add(literalOperator.clone(prefix, suffix));
parameters.remove(0);
}
final Expression<?> result = converter.convert(this);
Collections.copy(parameters, paramCopy);
return result;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFunctionCall#getFunction()
*/
@Override
public MethodKind getFunction() {
return methodCall;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFunctionCall#getParameter(int)
*/
@Override
public JPAOperator getParameter(final int index) {
return parameters.get(index);
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.filter.JPAFunctionCall#noParameters()
*/
@Override
public int noParameters() {
return parameters.size();
}
@Override
public String getName() {
return methodCall.name();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAUnaryBooleanOperator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPAUnaryBooleanOperator.java | package com.sap.olingo.jpa.processor.core.filter;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.UnaryOperatorKind;
public interface JPAUnaryBooleanOperator extends JPAExpressionOperator {
@Override
public Expression<Boolean> get() throws ODataApplicationException;
public Expression<Boolean> getLeft() throws ODataApplicationException;
@SuppressWarnings("unchecked")
@Override
public UnaryOperatorKind getOperator();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPACountExpression.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/filter/JPACountExpression.java | package com.sap.olingo.jpa.processor.core.filter;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitor;
import org.apache.olingo.server.api.uri.queryoption.expression.Literal;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
/**
* Expression for filter on navigation count. E.g.:<br>
* $filter=navigation/$count ge 2
* @author Oliver Grande
* @since 1.1.1
* 13.07.2023
*/
public class JPACountExpression extends JPAInvertibleVisitableExpression {
public JPACountExpression(final Member member, final Literal literal, final BinaryOperatorKind operator)
throws ODataJPAFilterException {
super(literal, operator, member);
}
@Override
public <T> T accept(final ExpressionVisitor<T> visitor) throws ExpressionVisitException, ODataApplicationException {
final T left = visitor.visitMember(member);
final T right = visitor.visitLiteral(literal);
return visitor.visitBinaryOperator(operator, left, right);
}
BinaryOperatorKind getOperator() {
return operator;
}
@Override
protected BinaryOperatorKind determineOperator(final BinaryOperatorKind operator, final Literal literal)
throws ODataJPAFilterException {
if ("0".equals(literal.getText())) {
if (operator == BinaryOperatorKind.EQ
|| operator == BinaryOperatorKind.LE) {
setInversionRequired(true);
return BinaryOperatorKind.NE;
} else if (operator == BinaryOperatorKind.GE) {
throw new ODataJPAFilterException(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_FILTER,
HttpStatusCode.BAD_REQUEST, ".../$count ge 0");
}
}
return operator;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubCountQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubCountQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static java.util.Collections.emptyList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaQuery;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
/**
* Requires Processor Query
*
* @author Oliver Grande
* @since 1.0.1
* 25.11.2020
*/
public final class JPAExpandSubCountQuery extends JPAAbstractExpandSubQuery implements JPAExpandCountQuery {
public JPAExpandSubCountQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAEntityType et, final JPAAssociationPath association, final List<JPANavigationPropertyInfo> hops)
throws ODataException {
super(odata, requestContext, et, association, copyHops(hops));
}
public JPAExpandSubCountQuery(final OData odata, final JPAExpandItemInfo item,
final JPAODataRequestContextAccess requestContext) throws ODataException {
super(odata, requestContext, item);
}
@Override
public final Map<String, Long> count() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "count")) {
final ProcessorCriteriaQuery<Tuple> tupleQuery = (ProcessorCriteriaQuery<Tuple>) cb.createTupleQuery();
addFilterCompiler(lastInfo);
final LinkedList<JPAAbstractQuery> hops = buildSubQueries(this);
final Subquery<Object> subQuery = linkSubQueries(hops);
createFromClause(emptyList(), emptyList(), tupleQuery, lastInfo);
final List<Selection<?>> selectionPath = createSelectClause();
tupleQuery.multiselect(addCount(selectionPath));
tupleQuery.where(createWhere(subQuery, lastInfo));
tupleQuery.groupBy(buildExpandCountGroupBy(root));
final TypedQuery<Tuple> query = em.createQuery(tupleQuery);
final List<Tuple> intermediateResult = query.getResultList();
return convertCountResult(intermediateResult);
} catch (final ODataException | JPANoSelectionException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private List<Selection<?>> createSelectClause() throws ODataApplicationException {
if (association.hasJoinTable()) {
return addSelectJoinTable(List.of());
} else
return buildExpandJoinPath(root);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionQueryResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionQueryResult.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
import com.sap.olingo.jpa.processor.core.converter.JPACollectionResult;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollection;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
public class JPACollectionQueryResult implements JPACollectionResult, JPAConvertibleResult {
private static final Map<String, List<Tuple>> EMPTY_RESULT;
private final Map<JPAAssociationPath, JPAExpandResult> childrenResult;
private final Map<String, List<Tuple>> jpaResult;
private Map<String, List<Object>> collectionResult;
private final Map<String, Long> counts;
private final JPAEntityType jpaEntityType;
private final JPAAssociationPath association;
private final Collection<JPAPath> requestedSelection;
static {
EMPTY_RESULT = new HashMap<>(1);
putEmptyResult();
}
/**
* Add an empty list as result for root to the EMPTY_RESULT. This is needed, as the conversion eats up the database
* result.
* @see JPATupleChildConverter
* @return
*/
private static Map<String, List<Tuple>> putEmptyResult() {
EMPTY_RESULT.put(ROOT_RESULT_KEY, Collections.emptyList());
return EMPTY_RESULT;
}
public JPACollectionQueryResult(final JPAEntityType jpaEntityType, final JPAAssociationPath association,
final Collection<JPAPath> selectionPath) {
this(putEmptyResult(), Collections.emptyMap(), jpaEntityType, association, selectionPath);
}
public JPACollectionQueryResult(final Map<String, List<Tuple>> result, final Map<String, Long> counts,
final JPAEntityType jpaEntityType, final JPAAssociationPath association,
final Collection<JPAPath> selectionPath) {
super();
this.childrenResult = new HashMap<>(1);
this.jpaResult = result;
this.counts = counts;
this.jpaEntityType = jpaEntityType;
this.association = association;
this.requestedSelection = selectionPath;
}
@Override
public Map<String, JPAEntityCollectionExtension> asEntityCollection(final JPAResultConverter converter)
throws ODataApplicationException {
this.collectionResult = converter.getCollectionResult(this, requestedSelection);
final Map<String, JPAEntityCollectionExtension> result = new HashMap<>(1);
final JPAEntityCollection collection = new JPAEntityCollection();
final Entity odataEntity = new Entity();
final JPAAttribute leaf = (JPAAttribute) association.getPath().get(association.getPath().size() - 1);
odataEntity.getProperties().add(new Property(
null,
leaf.getExternalName(),
leaf.isComplex() ? ValueType.COLLECTION_COMPLEX : ValueType.COLLECTION_PRIMITIVE,
collectionResult.get(ROOT_RESULT_KEY) != null ? collectionResult.get(ROOT_RESULT_KEY) : Collections
.emptyList()));
collection.getEntities().add(odataEntity);
result.put(ROOT_RESULT_KEY, collection);
return result;
}
@Override
public void convert(final JPAResultConverter converter) throws ODataApplicationException {
if (this.collectionResult == null)
this.collectionResult = converter.getCollectionResult(this, requestedSelection);
}
@Override
public JPAAssociationPath getAssociation() {
return association;
}
@Override
public JPAExpandResult getChild(final JPAAssociationPath associationPath) {
return null;
}
@Override
public Map<JPAAssociationPath, JPAExpandResult> getChildren() {
return childrenResult;
}
@Override
public Long getCount(final String key) {
return counts != null ? counts.get(key) : null;
}
@Override
public JPAEntityType getEntityType() {
return jpaEntityType;
}
@Override
public List<Object> getPropertyCollection(final String key) {
return collectionResult.containsKey(key) ? collectionResult.get(key) : Collections.emptyList();
}
@Override
public List<Tuple> getResult(final String key) {
return jpaResult.get(key);
}
@Override
public List<Tuple> removeResult(final String key) {
return jpaResult.remove(key);
}
@Override
public Map<String, List<Tuple>> getResults() {
return jpaResult;
}
@Override
public boolean hasCount() {
return counts != null;
}
@Override
public void putChildren(final Map<JPAAssociationPath, JPAExpandResult> childResults)
throws ODataApplicationException {
// Not needed yet. Collections with navigation properties not supported
}
@Override
public String getSkipToken(final List<JPAODataPageExpandInfo> foreignKeyStack) {
// No paging support for collection properties yet
return null;
}
@Override
public Collection<JPAPath> getRequestedSelection() {
return requestedSelection;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionItemInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionItemInfo.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
public final class JPACollectionItemInfo extends JPAInlineItemInfo {
JPACollectionItemInfo(final JPAServiceDocument sd, final JPAExpandItem uriInfo,
final JPAAssociationPath expandAssociation, final List<JPANavigationPropertyInfo> parentHops) {
super(uriInfo, expandAssociation, parentHops);
for (final JPANavigationPropertyInfo predecessor : parentHops)
this.hops.add(new JPANavigationPropertyInfo(predecessor));
this.hops.get(this.hops.size() - 1).setAssociationPath(expandAssociation);
this.hops.add(new JPANavigationPropertyInfo(sd, expandAssociation, uriInfo, uriInfo.getEntityType()));
}
@Override
public String toString() {
return "JPACollectionItemInfo [expandAssociation=" + expandAssociation + "]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItem.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItem.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.ApplyOption;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption;
import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.FormatOption;
import org.apache.olingo.server.api.uri.queryoption.IdOption;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
public interface JPAExpandItem extends UriInfoResource {
@Override
default ApplyOption getApplyOption() {
return null;
}
@Override
default CountOption getCountOption() {
return null;
}
@Override
default List<CustomQueryOption> getCustomQueryOptions() {
return new ArrayList<>(0);
}
@Override
default DeltaTokenOption getDeltaTokenOption() {
return null;
}
@Override
default ExpandOption getExpandOption() {
return null;
}
@Override
default FilterOption getFilterOption() {
return null;
}
@Override
default FormatOption getFormatOption() {
return null;
}
@Override
default IdOption getIdOption() {
return null;
}
@Override
default OrderByOption getOrderByOption() {
return null;
}
@Override
default SearchOption getSearchOption() {
return null;
}
@Override
default SelectOption getSelectOption() {
return null;
}
@Override
default SkipOption getSkipOption() {
return null;
}
@Override
default SkipTokenOption getSkipTokenOption() {
return null;
}
@Override
default TopOption getTopOption() {
return null;
}
default JPAEntityType getEntityType() {
return null;
}
default Optional<JPAODataSkipTokenProvider> getSkipTokenProvider() {
return Optional.empty();
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/ComparableByteArray.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/ComparableByteArray.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Arrays;
class ComparableByteArray implements Comparable<byte[]> {
private final byte[] bytes;
private final String value;
static byte[] unboxedArray(final Object object) {
if (object instanceof final Byte[] input) {
final byte[] result = new byte[input.length];
for (int i = 0; i < input.length; i++) {
result[i] = input[i]; // NOSONAR
}
return result;
} else if (object instanceof final byte[] bytes)
return bytes;
else
throw new IllegalArgumentException("Method called with wrong Type");
}
ComparableByteArray(final byte[] bytes) {
super();
this.bytes = bytes;
this.value = new String(unboxedArray(bytes));
}
@Override
public int compareTo(final byte[] o) {
return value.compareTo(new String(o));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(bytes);
return result;
}
@Override
public boolean equals(final Object object) {
if (this == object) return true;
if (!(object instanceof ComparableByteArray)) return false; // NOSONAR
final ComparableByteArray other = (ComparableByteArray) object;
return Arrays.equals(bytes, other.bytes);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys;
public class JPANavigationFilterQuery extends JPANavigationSubQuery implements ExistsExpressionValue {
JPANavigationFilterQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntityType,
final JPAAbstractQuery parent, final EntityManager em, final JPAAssociationPath association,
final From<?, ?> from, final Optional<JPAODataClaimProvider> claimsProvider,
final List<UriParameter> keyPredicates) throws ODataApplicationException {
super(odata, sd, jpaEntityType, em, parent, from, association,
claimsProvider, keyPredicates);
this.filterComplier = null;
this.aggregationType = null;
}
JPANavigationFilterQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntityType,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final Optional<JPAODataClaimProvider> claimsProvider,
final List<UriParameter> keyPredicates) throws ODataApplicationException {
super(odata, sd, jpaEntityType, em, parent, from, association, claimsProvider, keyPredicates);
}
/**
* Creates a exist sub query including the where clause joining this query with the parent query
*/
@Override
@SuppressWarnings("unchecked")
public <T extends Object> Subquery<T> getSubQuery(final Subquery<?> childQuery,
final VisitableExpression expression, final List<Path<Comparable<?>>> inPath) throws ODataApplicationException {
if (this.association.getJoinTable() != null) {
if (isCollectionProperty)
createSubQueryCollectionProperty(childQuery, expression, inPath);
else
createSubQueryJoinTable();
} else {
createSubQuery(childQuery, expression, inPath);
}
return (Subquery<T>) this.subQuery;
}
protected <T> void createSubQueryCollectionProperty(final Subquery<T> childQuery,
@Nullable final VisitableExpression expression, final List<Path<Comparable<?>>> inPath)
throws ODataApplicationException {
if (association.getTargetType() == null) {
createSubQueryCollectionNoTargetType();
} else {
createSubQueryCollectionWithTargetType(childQuery, expression, inPath);
}
}
private void createSubQueryCollectionNoTargetType() throws ODataApplicationException {
debugger.debug(this,
"Collection property without entity type: queries using such properties in the filter are not supported");
throw new ODataJPAQueryException(
MessageKeys.QUERY_PREPARATION_COLLECTION_PROPERTY_NOT_SUPPORTED, HttpStatusCode.BAD_REQUEST);
}
/**
* <pre>
* SELECT E0."ID" S0, E0."ETag" S1
* FROM "OLINGO"."BusinessPartner" E0
* WHERE EXISTS (
* SELECT E2."BusinessPartnerID" S0
* FROM "OLINGO"."Comment" E2
* WHERE (E2."BusinessPartnerID" = E0."ID"
* AND (E2."Text" LIKE '%just%')))
* </pre>
*
* @throws ODataApplicationException
*/
@SuppressWarnings("unchecked")
private <T> void createSubQueryCollectionWithTargetType(final Subquery<T> childQuery,
@Nullable final VisitableExpression expression, final List<Path<Comparable<?>>> inPath)
throws ODataApplicationException {
createSelectClauseJoin(subQuery, queryRoot, determineAggregationRightColumns(), false);
Expression<Boolean> whereCondition = addWhereClause(
createWhereByAssociation(from, queryRoot, determineJoinColumns()),
createWhereByKey(queryRoot, this.keyPredicates, jpaEntity));
if (childQuery != null) {
whereCondition = cb.and(whereCondition,
ExpressionUtility.createSubQueryBasedExpression((Subquery<List<Comparable<?>>>) childQuery, inPath, cb,
expression));
}
whereCondition = addWhereClause(whereCondition,
createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot));
subQuery.where(applyAdditionalFilter(whereCondition));
}
@SuppressWarnings("unchecked")
protected <T> void createSubQuery(final Subquery<T> childQuery,
@Nullable final VisitableExpression expression, final List<Path<Comparable<?>>> inPath)
throws ODataApplicationException {
createSelectClauseJoin(subQuery, queryRoot, determineAggregationRightColumns(), false);
Expression<Boolean> whereCondition = addWhereClause(
createWhereByAssociation(from, queryRoot, determineJoinColumns()),
createWhereByKey(queryRoot, this.keyPredicates, jpaEntity));
if (childQuery != null) {
whereCondition = cb.and(whereCondition,
ExpressionUtility.createSubQueryBasedExpression((Subquery<List<Comparable<?>>>) childQuery, inPath, cb,
expression));
}
whereCondition = addWhereClause(whereCondition,
createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot));
subQuery.where(applyAdditionalFilter(whereCondition));
}
/**
* <pre>
* SELECT t0."TeamKey"
* FROM "OLINGO"."Team" t0
* WHERE (EXISTS (
* SELECT t2."TeamID"
* FROM "OLINGO"."BusinessPartner" t1, "OLINGO"."Membership" t2
* WHERE t2."TeamID" = t0."TeamKey"
* AND t1."ID" = t2."PersonID"
* AND t1."Type" = '1'
* AND t1."NameLine2" = 'Mustermann'))
* </pre>
*/
protected void createSubQueryJoinTable() throws ODataApplicationException {
try {
final List<JPAOnConditionItem> left = association
.getJoinTable()
.getJoinColumns(); // Team -->
final List<JPAOnConditionItem> right = association
.getJoinTable()
.getInverseJoinColumns(); // Person -->
createSelectClauseJoin(subQuery, queryRoot, determineAggregationRightColumns(), false);
Expression<Boolean> whereCondition = createWhereByAssociation(from, queryJoinTable, left);
whereCondition = cb.and(whereCondition, createWhereByAssociation(queryJoinTable, queryRoot, right));
whereCondition = addWhereClause(whereCondition, createProtectionWhereForEntityType(claimsProvider, jpaEntity,
queryRoot));
subQuery.where(applyAdditionalFilter(whereCondition));
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAInlineItemInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAInlineItemInfo.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.apache.olingo.server.api.uri.UriInfoResource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
public abstract class JPAInlineItemInfo {
protected final JPAExpandItem uriInfo;
protected final JPAAssociationPath expandAssociation;
protected final List<JPANavigationPropertyInfo> hops;
protected final List<JPANavigationPropertyInfo> parentHops;
JPAInlineItemInfo(@Nonnull final JPAExpandItem uriInfo, @Nonnull final JPAAssociationPath expandAssociation,
@Nonnull final List<JPANavigationPropertyInfo> parentHops) {
this.uriInfo = uriInfo;
this.expandAssociation = expandAssociation;
this.parentHops = parentHops;
this.hops = new ArrayList<>();
}
public UriInfoResource getUriInfo() {
return uriInfo;
}
public JPAAssociationPath getExpandAssociation() {
return expandAssociation;
}
public List<JPANavigationPropertyInfo> getHops() {
return Collections.unmodifiableList(hops);
}
public JPAEntityType getEntityType() {
return uriInfo.getEntityType();
}
public Optional<JPAODataSkipTokenProvider> getSkipTokenProvider() {
return uriInfo.getSkipTokenProvider();
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractExpandQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractExpandQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJoinTable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public abstract class JPAAbstractExpandQuery extends JPAAbstractJoinQuery {
protected final JPAAssociationPath association;
protected final Optional<JPAODataSkipTokenProvider> skipTokenProvider;
static List<JPANavigationPropertyInfo> copyHops(final List<JPANavigationPropertyInfo> hops) {
return hops.stream()
.map(JPANavigationPropertyInfo::new)
.toList();
}
JPAAbstractExpandQuery(final OData odata,
final JPAEntityType jpaEntityType, final JPAODataRequestContextAccess requestContext,
final JPAAssociationPath association) throws ODataException {
super(odata, jpaEntityType, requestContext, emptyList());
this.association = association;
this.skipTokenProvider = Optional.empty();
}
JPAAbstractExpandQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAInlineItemInfo item) throws ODataException {
super(odata, item.getEntityType(), item.getUriInfo(), requestContext, item.getHops());
this.association = item.getExpandAssociation();
this.skipTokenProvider = item.getSkipTokenProvider();
}
JPAAbstractExpandQuery(final OData odata, final JPAODataRequestContextAccess requestContext, final JPAEntityType et,
final JPAAssociationPath association, final List<JPANavigationPropertyInfo> hops) throws ODataException {
super(odata, et, requestContext, hops);
this.association = association;
this.skipTokenProvider = Optional.empty();
}
@Override
protected SelectionPathInfo<JPAPath> buildSelectionPathList(final UriInfoResource uriResource)
throws ODataApplicationException {
try {
final SelectionPathInfo<JPAPath> jpaPathList = super.buildSelectionPathList(uriResource);
debugger.trace(this, "The following selection path elements were found: %s", jpaPathList.toString());
return new SelectionPathInfo<>(association.getRightColumnsList(), jpaPathList);
} catch (final ODataJPAModelException e) {
throw new ODataApplicationException(e.getLocalizedMessage(), HttpStatusCode.INTERNAL_SERVER_ERROR
.getStatusCode(), ODataJPAException.getLocales().nextElement(), e);
}
}
protected String buildConcatenatedKey(final Tuple row, final JPAAssociationPath association)
throws ODataJPAModelException {
if (!association.hasJoinTable()) {
final List<JPAPath> joinColumns = association.getRightColumnsList();
return joinColumns.stream()
.map(column -> (row.get(column
.getAlias()))
.toString())
.collect(joining(JPAPath.PATH_SEPARATOR));
} else {
final List<JPAPath> joinColumns = association.getLeftColumnsList();
return joinColumns.stream()
.map(column -> (row.get(association.getAlias() + ALIAS_SEPARATOR + column.getAlias())).toString())
.collect(joining(JPAPath.PATH_SEPARATOR));
}
}
protected List<Order> createOrderByJoinCondition(final JPAAssociationPath associationPath)
throws ODataApplicationException {
final List<Order> orders = new ArrayList<>();
try {
final List<JPAPath> joinColumns = associationPath.hasJoinTable()
? associationPath.getLeftColumnsList() : associationPath.getRightColumnsList();
final From<?, ?> from = associationPath.hasJoinTable() ? determineParentFrom() : target;
for (final JPAPath j : joinColumns) {
Path<?> jpaProperty = from;
for (final JPAElement pathElement : j.getPath()) {
jpaProperty = jpaProperty.get(pathElement.getInternalName());
}
orders.add(cb.asc(jpaProperty));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
return orders;
}
@SuppressWarnings("unchecked")
protected <S, T> From<S, T> determineParentFrom() throws ODataJPAQueryException {
for (final JPANavigationPropertyInfo item : this.navigationInfo) {
if (item.getAssociationPath() == association)
return (From<S, T>) item.getFromClause();
}
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR,
HttpStatusCode.BAD_REQUEST);
}
protected List<Expression<?>> buildExpandCountGroupBy(final From<?, ?> root) throws ODataJPAQueryException {
if (association.hasJoinTable()) {
return buildExpandCountGroupByJoinTable(root);
} else
return buildExpandCountGroupByJoin(root);
}
private List<Expression<?>> buildExpandCountGroupByJoin(final From<?, ?> root)
throws ODataJPAQueryException {
final List<Expression<?>> groupBy = new ArrayList<>();
try {
final List<JPAOnConditionItem> associationPathList = association.getJoinColumnsList();
for (final JPAOnConditionItem onCondition : associationPathList) {
groupBy.add(ExpressionUtility.convertToCriteriaPath(root, onCondition.getRightPath().getPath()));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
return groupBy;
}
private List<Expression<?>> buildExpandCountGroupByJoinTable(final From<?, ?> root)
throws ODataJPAQueryException {
final List<Expression<?>> groupBy = new ArrayList<>();
final JPAJoinTable joinTable = association.getJoinTable();
try {
for (final JPAOnConditionItem onCondition : joinTable.getJoinColumns()) {
groupBy.add(ExpressionUtility.convertToCriteriaPath(root, onCondition.getRightPath().getPath()));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
return groupBy;
}
abstract Map<String, Long> count() throws ODataApplicationException;
protected boolean countRequested(final JPANavigationPropertyInfo lastInfo) {
if (lastInfo.getUriInfo() == null)
return false;
final CountOption count = lastInfo.getUriInfo().getCountOption();
final List<UriResource> parts = lastInfo.getUriInfo().getUriResourceParts();
return count != null && count.getValue()
|| parts.size() > 1
&& parts.get(parts.size() - 1).getKind() == UriResourceKind.count;
}
protected List<Selection<?>> buildExpandJoinPath(final From<?, ?> root) throws ODataApplicationException {
final List<Selection<?>> selections = new ArrayList<>();
try {
final List<JPAOnConditionItem> associationPathList = association.getJoinColumnsList();
for (final JPAOnConditionItem onCondition : associationPathList) {
final Path<?> p = ExpressionUtility.convertToCriteriaPath(root, onCondition.getRightPath().getPath());
p.alias(onCondition.getRightPath().getAlias());
selections.add(p);
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
return selections;
}
protected Map<String, Long> convertCountResult(final List<Tuple> intermediateResult) throws ODataJPAQueryException {
final Map<String, Long> result = new HashMap<>();
for (final Tuple row : intermediateResult) {
try {
final String actualKey = buildConcatenatedKey(row, association);
final Number count = (Number) row.get(COUNT_COLUMN_NAME);
result.put(actualKey, count.longValue());
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
return result;
}
protected final List<Selection<?>> addCount(final List<Selection<?>> selectionPath) {
final Expression<Long> count = cb.count(target);
count.alias(COUNT_COLUMN_NAME);
selectionPath.add(count);
return selectionPath;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionExpandWrapper.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionExpandWrapper.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption;
import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.FormatOption;
import org.apache.olingo.server.api.uri.queryoption.IdOption;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
public class JPACollectionExpandWrapper implements JPAExpandItem {
private final JPAEntityType jpaEntityType;
private final UriInfoResource uriInfo;
private final SelectOption selectOption;
JPACollectionExpandWrapper(final JPAEntityType jpaEntityType, final UriInfoResource uriInfo,
final JPAAssociationPath associationPath) {
super();
this.jpaEntityType = jpaEntityType;
this.uriInfo = uriInfo;
this.selectOption = buildSelectOption(uriInfo.getSelectOption(), associationPath);
}
public JPACollectionExpandWrapper(final JPAEntityType jpaEntityType, final UriInfoResource uriInfo) {
this.jpaEntityType = jpaEntityType;
this.uriInfo = uriInfo;
this.selectOption = uriInfo.getSelectOption();
}
@Override
public List<CustomQueryOption> getCustomQueryOptions() {
return new ArrayList<>(0);
}
@Override
public ExpandOption getExpandOption() {
return null;
}
@Override
public FilterOption getFilterOption() {
return uriInfo.getFilterOption();
}
@Override
public FormatOption getFormatOption() {
return null;
}
@Override
public IdOption getIdOption() {
return null;
}
@Override
public CountOption getCountOption() {
return uriInfo.getCountOption();
}
@Override
public DeltaTokenOption getDeltaTokenOption() {
return null;
}
@Override
public OrderByOption getOrderByOption() {
return null;
}
@Override
public SearchOption getSearchOption() {
return null;
}
@Override
public SelectOption getSelectOption() {
return selectOption;
}
@Override
public List<UriResource> getUriResourceParts() {
return uriInfo.getUriResourceParts();
}
@Override
public String getValueForAlias(final String alias) {
return null;
}
@Override
public JPAEntityType getEntityType() {
return jpaEntityType;
}
@Override
public Optional<JPAODataSkipTokenProvider> getSkipTokenProvider() {
return Optional.empty();
}
private SelectOption buildSelectOption(final SelectOption selectOption, final JPAAssociationPath associationPath) {
final JPACollectionAttribute collectionAttribute = (JPACollectionAttribute) associationPath.getLeaf();
final List<SelectItem> itemsOfProperty = selectOption.getSelectItems().stream()
.filter(item -> containsCollectionProperty(collectionAttribute, item.getResourcePath()))
.toList();
return new SelectOptionImpl(selectOption.getKind(), selectOption.getName(), selectOption.getText(),
itemsOfProperty);
}
private boolean containsCollectionProperty(final JPACollectionAttribute collectionAttribute,
final UriInfoResource resourcePath) {
return resourcePath.getUriResourceParts().stream()
.anyMatch(part -> part.getSegmentValue().equals(collectionAttribute.getExternalName()));
}
private static class SelectOptionImpl implements SelectOption {
private final SystemQueryOptionKind kind;
private final String name;
private final String text;
private final List<SelectItem> items;
public SelectOptionImpl(final SystemQueryOptionKind kind, final String name, final String text,
final List<SelectItem> itemsOfProperty) {
this.kind = kind;
this.name = name;
this.text = text;
this.items = itemsOfProperty;
}
@Override
public SystemQueryOptionKind getKind() {
return kind;
}
@Override
public String getName() {
return name;
}
@Override
public String getText() {
return text;
}
@Override
public List<SelectItem> getSelectItems() {
return items;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractRootJoinQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractRootJoinQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ENTITY_UNKNOWN;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.AbstractQuery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
abstract class JPAAbstractRootJoinQuery extends JPAAbstractJoinQuery {
private static List<JPANavigationPropertyInfo> determineNavigationInfo(
final JPAServiceDocument sd, final UriInfoResource uriResource)
throws ODataException {
return Utility.determineNavigationPath(sd, uriResource.getUriResourceParts(), uriResource);
}
private static JPAEntityType determineTargetEntityType(final JPAODataRequestContextAccess requestContext)
throws ODataException {
final var resources = requestContext.getUriInfo().getUriResourceParts();
final var bindingTarget = Utility.determineBindingTarget(resources);
if (bindingTarget instanceof EdmBoundCast) {
return requestContext.getEdmProvider().getServiceDocument().getEntity(bindingTarget.getEntityType());
}
return requestContext.getEdmProvider().getServiceDocument().getEntity(bindingTarget.getName());
}
@Nonnull
protected static JPAEntityType determineODataTargetEntityType(final JPAODataRequestContextAccess requestContext)
throws ODataApplicationException {
final var resources = requestContext.getUriInfo().getUriResourceParts();
try {
final var bindingTarget = Utility.determineBindingTarget(resources);
return Optional.ofNullable(requestContext.getEdmProvider().getServiceDocument() // NOSONAR
.getEntity(bindingTarget.getEntityType()))
.orElseThrow(() -> new ODataJPAQueryException(QUERY_PREPARATION_ENTITY_UNKNOWN, INTERNAL_SERVER_ERROR,
bindingTarget.getEntityType().getName()));
} catch (final ODataException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
JPAAbstractRootJoinQuery(final OData odata, final JPAEntityType entityType,
final JPAODataRequestContextAccess requestContext, final List<JPANavigationPropertyInfo> determineNavigationInfo)
throws ODataException {
super(odata, entityType, requestContext, determineNavigationInfo);
}
JPAAbstractRootJoinQuery(final OData odata, final JPAODataRequestContextAccess requestContext) throws ODataException {
super(odata, determineTargetEntityType(requestContext),
requestContext, determineNavigationInfo(requestContext.getEdmProvider().getServiceDocument(), requestContext
.getUriInfo()));
entitySet = determineTargetEntitySet(requestContext);
}
@SuppressWarnings("unchecked")
@Override
public AbstractQuery<Tuple> getQuery() {
return cq;
}
protected jakarta.persistence.criteria.Expression<Boolean> createWhere() throws ODataApplicationException {
final var filter = super.createWhere(uriResource, navigationInfo);
return addWhereClause(filter, createProtectionWhere(claimsProvider));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/EdmBindingTargetInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/EdmBindingTargetInfo.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.server.api.uri.UriParameter;
public interface EdmBindingTargetInfo {
public EdmBindingTarget getEdmBindingTarget();
public List<UriParameter> getKeyPredicates();
public String getName();
public String getNavigationPath();
public EdmBindingTarget getTargetEdmBindingTarget();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandFilterQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandFilterQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NO_JOIN_TABLE_TYPE;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_UNSUPPORTED_EXPAND;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJoinTable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterCrossComplier;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterRestrictionsWatchDog;
import com.sap.olingo.jpa.processor.core.filter.JPAOperationConverter;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
class JPAExpandFilterQuery extends JPAAbstractSubQuery {
final List<UriParameter> keyPredicates;
final JPAODataRequestContextAccess requestContext;
final List<JPANavigationPropertyInfo> navigationInfo;
final JPANavigationPropertyInfo lastInfo;
final Optional<JPAAssociationPath> childAssociation;
final Map<String, From<?, ?>> joinTables;
private static List<JPANavigationPropertyInfo> determineNavigationInfo(
final JPAServiceDocument sd, final JPANavigationPropertyInfo navigationInfo)
throws ODataException {
final var uriInfo = navigationInfo.getUriInfo();
return Utility.determineNavigationPath(sd, uriInfo.getUriResourceParts(), uriInfo);
}
JPAExpandFilterQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPANavigationPropertyInfo navigationInfo, final JPAAbstractQuery parent,
final JPAAssociationPath childAssociation) throws ODataException {
this(odata, requestContext, navigationInfo, parent, navigationInfo.getAssociationPath(), childAssociation);
}
public JPAExpandFilterQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPANavigationPropertyInfo navigationInfo, final JPAAbstractQuery parent,
final JPAAssociationPath association,
final JPAAssociationPath childAssociation) throws ODataException {
super(odata,
requestContext.getEdmProvider().getServiceDocument(),
navigationInfo.getEntityType(),
requestContext.getEntityManager(),
parent,
null,
association,
requestContext.getClaimsProvider());
this.requestContext = requestContext;
this.keyPredicates = navigationInfo.getKeyPredicates();
this.subQuery = parent.getQuery().subquery(this.jpaEntity.getKeyType());
this.locale = parent.getLocale();
this.navigationInfo = determineNavigationInfo(sd, navigationInfo);
this.lastInfo = this.navigationInfo.get(this.navigationInfo.size() - 1);
this.lastInfo.setAssociationPath(navigationInfo.getAssociationPath());
this.childAssociation = Optional.ofNullable(childAssociation);
this.joinTables = new HashMap<>();
this.debugger = requestContext.getDebugger();
setFilter(this.lastInfo);
}
@SuppressWarnings("unchecked")
@Override
public From<?, ?> getRoot() {
return queryRoot;
}
/**
*
*/
@SuppressWarnings("unchecked")
@Nonnull
@Override
public <T> Subquery<T> getSubQuery(@Nullable final Subquery<?> childQuery,
final VisitableExpression expression, final List<Path<Comparable<?>>> inPath) throws ODataApplicationException {
// Last childQuery == null
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createSubQuery")) {
final ProcessorSubquery<T> nextQuery = (ProcessorSubquery<T>) this.subQuery;
final JPAQueryPair queries = createQueries(childQuery);
final var orderByAttributes = getOrderByAttributes(lastInfo.getUriInfo().getOrderByOption());
createRoots(childQuery, queries, nextQuery);
buildJoinTable(orderByAttributes, emptyList(), childQuery);
final List<JPAPath> selections = selectionPathIn();
nextQuery.where(createWhere(childQuery));
nextQuery.multiselect(selectIn(childQuery, selections));
nextQuery.orderBy(createOrderBy(childQuery, orderByAttributes));
nextQuery.setFirstResult(getSkipValue(childQuery));
nextQuery.setMaxResults(getTopValue(childQuery));
nextQuery.groupBy(createGroupBy(joinTables, queryRoot, selections, orderByAttributes));
return nextQuery;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
protected final JPAFilterCrossComplier addFilterCompiler(final JPANavigationPropertyInfo navigationInfo)
throws ODataJPAModelException, ODataJPAProcessorException, ODataJPAQueryException {
final JPAOperationConverter converter = new JPAOperationConverter(cb, requestContext.getOperationConverter(),
requestContext.getQueryDirectives());
final JPAODataRequestContextAccess subContext = new JPAODataInternalRequestContext(navigationInfo.getUriInfo(),
requestContext);
final JPAFilterRestrictionsWatchDog watchDog = new JPAFilterRestrictionsWatchDog(this.association.getLeaf(),
!navigationInfo.getKeyPredicates().isEmpty());
return new JPAFilterCrossComplier(odata, sd, navigationInfo.getEntityType(), converter, this,
navigationInfo.getFromClause(), null, subContext, watchDog);
}
@Override
protected Expression<Boolean> applyAdditionalFilter(final Expression<Boolean> where)
throws ODataApplicationException {
if (lastInfo.getFilterCompiler() != null && aggregationType == null) {
try {
return addWhereClause(where, lastInfo.getFilterCompiler().compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
return where;
}
void buildJoinTable(final List<JPAProcessorAttribute> orderByAttributes, final Collection<JPAPath> selectionPath,
final Subquery<?> childQuery) throws ODataApplicationException {
createFromClauseNavigationJoins(joinTables);
createFromClauseJoinTable(joinTables, childQuery);
createFromClauseOrderBy(orderByAttributes, joinTables, queryRoot);
createFromClauseDescriptionFields(selectionPath, joinTables, queryRoot, singletonList(lastInfo));
}
protected final void createFromClauseNavigationJoins(final Map<String, From<?, ?>> joinTables)
throws ODataJPAQueryException {
for (int i = 0; i < this.navigationInfo.size(); i++) {
final JPANavigationPropertyInfo propertyInfo = this.navigationInfo.get(i);
propertyInfo.setFromClause(queryRoot);
if (this.navigationInfo.size() > i + 1) {
queryRoot = createJoinFromPath(propertyInfo.getAssociationPath().getAlias(), propertyInfo.getAssociationPath()
.getPath(), queryRoot, JoinType.INNER);
try {
final JPAEntityType cast = this.navigationInfo.get(i + 1).getEntityType();
if (derivedTypeRequested(propertyInfo.getAssociationPath().getTargetType(), cast))
queryRoot = (From<?, ?>) queryRoot.as(cast.getTypeClass());
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
joinTables.put(propertyInfo.getAssociationPath().getAlias(), queryRoot);
}
}
}
private void createFromClauseJoinTable(final Map<String, From<?, ?>> joinTables, final Subquery<?> childQuery) {
if (!hasRowLimit(childQuery)) {
final Optional<JPAEntityType> joinTableEt = childAssociation
.map(JPAAssociationPath::getJoinTable)
.map(JPAJoinTable::getEntityType);
joinTableEt.ifPresent(et -> {
debugger.trace(this, "Join table found: %s, join will be created", joinTableEt.toString());
queryJoinTable = subQuery.from(et.getTypeClass());
queryJoinTable.alias(association.getAlias());
joinTables.put(association.getAlias(), queryJoinTable);
});
}
}
void setFilter(final JPANavigationPropertyInfo navigationInfo) throws ODataJPAModelException,
ODataJPAProcessorException,
ODataJPAQueryException {
if (navigationInfo.getFilterCompiler() == null) {
navigationInfo.setFilterCompiler(addFilterCompiler(navigationInfo));
}
}
private List<Order> createOrderBy(final Subquery<?> childQuery, final List<JPAProcessorAttribute> orderByAttributes)
throws ODataApplicationException {
if (!hasRowLimit(childQuery)) {
final JPAOrderByBuilder orderByBuilder = new JPAOrderByBuilder(jpaEntity, queryRoot, cb, groups);
return orderByBuilder.createOrderByList(joinTables, orderByAttributes, lastInfo.getUriInfo());
}
return emptyList();
}
JPAQueryPair createQueries(@Nullable final Subquery<?> childQuery) throws ODataApplicationException {
if (hasRowLimit(lastInfo) && childQuery != null) {
debugger.trace(this, "Row number required");
JPARowNumberFilterQuery rowNumberQuery;
try {
rowNumberQuery = new JPARowNumberFilterQuery(odata, requestContext, lastInfo, parentQuery, childAssociation);
} catch (final ODataException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
return new JPAQueryPair(rowNumberQuery, this);
} else {
debugger.trace(this, "Row number not required");
return new JPAQueryPair(this, this);
}
}
void createRoots(final Subquery<?> childQuery, final JPAQueryPair queries,
final ProcessorSubquery<?> nextQuery) throws ODataJPAModelException, ODataApplicationException {
if (hasRowLimit(childQuery)) {
if (this.navigationInfo.size() == 1)
this.queryRoot = nextQuery.from((ProcessorSubquery<?>) ((JPARowNumberFilterQuery) queries.inner())
.getSubQuery(childQuery, null, Collections.emptyList()));
else
// Navigation within an expand is not supported and should have ended in an UriMalformed exception by Olingo
throw new ODataJPAQueryException(QUERY_PREPARATION_UNSUPPORTED_EXPAND, BAD_REQUEST);
} else {
this.queryRoot = subQuery.from(navigationInfo.get(0).getEntityType().getTypeClass());
}
joinTables.put(navigationInfo.get(0).getEntityType().getExternalFQN().getFullQualifiedNameAsString(), queryRoot);
}
private Expression<Boolean> createWhere(final Subquery<?> childQuery) throws ODataApplicationException {
if (hasRowLimit(childQuery)) {
return createWhereByRowNumber(queryRoot, lastInfo);
}
return createWhereSubQuery(childQuery, false);
}
Expression<Boolean> createWhereSubQuery(@Nullable final Subquery<?> childQuery, final boolean useInverse)
throws ODataApplicationException {
Expression<Boolean> whereCondition = createKeyWhere(navigationInfo);
whereCondition = addWhereClause(whereCondition, createProtectionWhereForEntityType(claimsProvider, jpaEntity,
queryRoot));
if (queryJoinTable != null) {
whereCondition = addWhereClause(whereCondition, createWhereTableJoin(queryJoinTable, queryRoot, association,
useInverse));
}
if (childQuery != null) {
whereCondition = addWhereClause(whereCondition,
createWhereKeyIn(childAssociation
.orElseThrow(() -> new ODataJPAQueryException(QUERY_PREPARATION_ERROR, INTERNAL_SERVER_ERROR)),
queryJoinTable == null ? queryRoot : queryJoinTable, childQuery));
}
return applyAdditionalFilter(whereCondition);
}
@Override
protected Expression<Boolean> createWhereEnhancement(final JPAEntityType et, final From<?, ?> from)
throws ODataJPAProcessorException {
final Optional<EdmQueryExtensionProvider> queryEnhancement = requestContext.getQueryEnhancement(et);
if (queryEnhancement.isPresent()) {
debugger.trace(this, "Query Enhancement found. Add WHERE condition of: %s", queryEnhancement.get().getClass()
.getName());
return queryEnhancement.get().getFilterExtension(cb, from);
}
return null;
}
private Integer getSkipValue(@Nullable final Subquery<?> childQuery) {
if (lastInfo.getUriInfo().getSkipOption() != null && childQuery == null) {
return lastInfo.getUriInfo().getSkipOption().getValue();
}
return null;
}
private Integer getTopValue(@Nullable final Subquery<?> childQuery) {
if (lastInfo.getUriInfo().getTopOption() != null && childQuery == null) {
return lastInfo.getUriInfo().getTopOption().getValue();
}
return null;
}
private boolean hasRowLimit(@Nullable final Subquery<?> childQuery) {
return super.hasRowLimit(lastInfo) && childQuery != null;
}
Expression<?> mapOnToSelection(final JPAPath on, final From<?, ?> root, @Nullable final Subquery<?> childQuery) {
final Path<?> path;
if (hasRowLimit(childQuery)) {
path = root.get(on.getAlias());
} else {
path = ExpressionUtility.convertToCriteriaPath(root, on.getPath());
}
path.alias(on.getLeaf().getInternalName());
return path;
}
private List<Selection<?>> selectIn(final Subquery<?> childQuery, final List<JPAPath> selections) {
return selections.stream()
.map(path -> mapOnToSelection(path, queryRoot, childQuery))
.collect(toList());// NOSONAR
}
private List<JPAPath> selectionPathIn() throws ODataJPAQueryException {
try {
final List<JPAOnConditionItem> columns = association.hasJoinTable()
? association.getJoinTable().getJoinColumns()
: association.getJoinColumnsList();
return columns.stream()
.map(JPAOnConditionItem::getLeftPath)
.toList();
} catch (final ODataJPAModelException e) {
if (e.getId().equals(NO_JOIN_TABLE_TYPE.getKey())) {
throw new ODataJPAQueryException(QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING, INTERNAL_SERVER_ERROR,
association.getJoinTable().getTableName());
}
throw new ODataJPAQueryException(QUERY_PREPARATION_ERROR, INTERNAL_SERVER_ERROR, e);
}
}
@Override
public List<Path<Comparable<?>>> getLeftPaths() throws ODataJPAIllegalAccessException {
return Collections.emptyList();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemInfoFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemInfoFactory.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ATTRIBUTE_NOT_FOUND;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.UriResourceSingleton;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public final class JPAExpandItemInfoFactory {
private static final int ST_INDEX = 0;
private static final int ET_INDEX = 1;
private static final int PROPERTY_INDEX = 2;
private static final int PATH_INDEX = 3;
private final JPAODataRequestContextAccess requestContext;
public JPAExpandItemInfoFactory(final JPAODataRequestContextAccess requestContext) {
this.requestContext = requestContext;
}
public List<JPAExpandItemInfo> buildExpandItemInfo(final JPAServiceDocument sd, final UriInfoResource uriResourceInfo,
final List<JPANavigationPropertyInfo> grandParentHops, final Optional<JPAKeyBoundary> keyBoundary,
final JPAExpandQueryFactory factory) throws ODataException {
final List<JPAExpandItemInfo> itemList = new ArrayList<>();
final List<UriResource> startResourceList = uriResourceInfo.getUriResourceParts();
final ExpandOption expandOption = uriResourceInfo.getExpandOption();
// ((UriResourceNavigation)
// uriResourceInfo.getExpandOption().getExpandItems().get(0).getResourcePath().getUriResourceParts().get(0)).getTypeFilterOnEntry()
if (startResourceList != null && expandOption != null) {
final List<JPANavigationPropertyInfo> parentHops = grandParentHops;
final Map<JPAExpandItem, JPAAssociationPath> expandPath = Utility.determineAssociations(sd, startResourceList,
expandOption);
for (final Entry<JPAExpandItem, JPAAssociationPath> item : expandPath.entrySet()) {
final var expandItem = new JPAExpandItemInfo(sd, item.getKey(), item.getValue(), parentHops);
final var count = factory.createCountQuery(expandItem, keyBoundary);
final var provider = requestContext.getPagingProvider();
final Optional<JPAODataExpandPage> page;
if (provider.isPresent())
page = provider.get().getFirstPageExpand(requestContext.getRequestParameter(),
requestContext.getPathInformation(), requestContext.getUriInfo(), item.getKey().getTopOption(), item
.getKey().getSkipOption(),
item.getValue().getLeaf(), count, requestContext.getEntityManager());
else
page = Optional.empty();
itemList.add(new JPAExpandItemInfo(expandItem, page));
}
}
return itemList;
}
/**
* Navigate to collection property e.g.<br>
* ../Organizations('1')/Comment or<br>
* ../CollectionDeeps?$select=FirstLevel/SecondLevel or<br>
* ../CollectionDeeps/FirstLevel
* ../CollectionDeeps/FirstLevel/SecondLevel?$select=...,...
*
* @param sd
* @param uriResourceInfo
* @param optional
* @param parentHops
* @return
* @throws ODataApplicationException
*/
public List<JPACollectionItemInfo> buildCollectionItemInfo(final JPAServiceDocument sd,
final UriInfoResource uriResourceInfo, final List<JPANavigationPropertyInfo> grandParentHops,
final Optional<JPAODataGroupProvider> groups) throws ODataApplicationException {
final List<JPACollectionItemInfo> itemList = new ArrayList<>();
final List<UriResource> startResourceList = uriResourceInfo.getUriResourceParts();
final SelectOption select = uriResourceInfo.getSelectOption();
final JPAEntityType et = uriResourceInfo instanceof final JPAExpandItem expandItem
? expandItem.getEntityType() : null;
final Object[] pathInfo = determineNavigationElements(sd, startResourceList, et);
try {
if (pathInfo[PROPERTY_INDEX] != null) {
if (((JPAPath) pathInfo[PROPERTY_INDEX]).getLeaf().isCollection()) {
// BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')/Organization/Comment
// Organizations('1')/Comment
// Persons('99')/InhouseAddress
// Persons('99')/InhouseAddress?$filter=TaskID eq 'DEV'
// Moved
}
} else {
// Organizations('1')?$select=Comment
// Et/St?$select=Cp
if (SelectOptionUtil.selectAll(select)) {
// No navigation, extract all collection attributes
final JPAStructuredType st = (JPAStructuredType) pathInfo[ST_INDEX];
final Set<JPACollectionAttribute> collectionProperties = new HashSet<>();
for (final JPAPath path : st.getPathList()) {
final StringBuilder pathName = new StringBuilder(pathInfo[PATH_INDEX].toString());
for (final JPAElement pathElement : path.getPath()) {
pathName.append(pathElement.getExternalName()).append(JPAPath.PATH_SEPARATOR);
if (pathElement instanceof final JPAAttribute attribute && attribute.isCollection()) {
if (path.isPartOfGroups(groups.isPresent() ? groups.get().getGroups() : new ArrayList<>(0))
&& !attribute.isTransient()) {
collectionProperties.add(getCollectionPath(pathInfo, pathName));
}
break;
}
}
}
for (final var pathElement : collectionProperties) {
final JPACollectionExpandWrapper item = new JPACollectionExpandWrapper((JPAEntityType) pathInfo[ET_INDEX],
uriResourceInfo);
itemList.add(new JPACollectionItemInfo(sd, item, pathElement.asAssociation(), grandParentHops));
}
} else {
// Et?$select=Cp
// Et/St?$select=Cp,Cp
// Et/St/St?$select=Cp
// Et/St?$select=St/Cp
final JPAStructuredType st = (JPAStructuredType) pathInfo[ST_INDEX];
final Set<JPAPath> selectOptions = getCollectionAttributesFromSelection(st, uriResourceInfo
.getSelectOption());
final Map<JPAPath, JPAAssociationPath> collectionPaths = Utility.determineAssociations(sd,
startResourceList, selectOptions);
for (final JPAAssociationPath path : collectionPaths.values()) {
final JPACollectionExpandWrapper item = new JPACollectionExpandWrapper((JPAEntityType) pathInfo[ET_INDEX],
uriResourceInfo, path);
itemList.add(new JPACollectionItemInfo(sd, item, path, grandParentHops));
}
}
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return itemList;
}
private JPACollectionAttribute getCollectionPath(final Object[] pathInfo, final StringBuilder pathName)
throws ODataJPAModelException, ODataJPAProcessorException {
final var name = pathName.deleteCharAt(pathName.length() - 1).toString();
final JPAPath collectionPath = ((JPAEntityType) pathInfo[ET_INDEX]).getPath(name);
if (collectionPath != null)
return (JPACollectionAttribute) collectionPath.getLeaf();
else
throw new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND, HttpStatusCode.INTERNAL_SERVER_ERROR, name);
}
private Object[] determineNavigationElements(final JPAServiceDocument sd,
final List<UriResource> startResourceList, final JPAEntityType et) throws ODataJPAQueryException {
StringBuilder path = new StringBuilder();
final Object[] result = new Object[4];
if (startResourceList.isEmpty() && et != null) {
result[ST_INDEX] = result[ET_INDEX] = et;
} else {
for (final UriResource uriElement : startResourceList) {
try {
if (uriElement instanceof UriResourceEntitySet || uriElement instanceof UriResourceSingleton
|| uriElement instanceof UriResourceNavigation) {
result[ST_INDEX] = result[ET_INDEX] = sd.getEntity(((UriResourcePartTyped) uriElement)
.getType());
path = new StringBuilder(); // Reset path on switch between entities
} else if (uriElement instanceof final UriResourceComplexProperty complexProperty
&& !complexProperty.isCollection()) {
result[ST_INDEX] = sd.getComplexType(complexProperty.getComplexType());
path.append(complexProperty.getProperty().getName())
.append(JPAPath.PATH_SEPARATOR);
} else if (uriElement instanceof final UriResourceProperty resourceProperty
&& result[ST_INDEX] != null) {
result[PROPERTY_INDEX] = ((JPAStructuredType) result[ST_INDEX]).getPath(resourceProperty
.getProperty().getName());
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
result[PATH_INDEX] = path;
return result;
}
private Set<JPAPath> getCollectionAttributesFromSelection(final JPAStructuredType jpaEntity,
final SelectOption select) throws ODataApplicationException, ODataJPAModelException {
final Set<JPAPath> collectionAttributes = new HashSet<>();
if (SelectOptionUtil.selectAll(select)) {
collectionAttributes.addAll(jpaEntity.getCollectionAttributesPath());
} else {
final String pathPrefix = "";
for (final SelectItem sItem : select.getSelectItems()) {
final JPAPath selectItemPath = SelectOptionUtil.selectItemAsPath(jpaEntity, pathPrefix, sItem);
if (selectItemPath.getLeaf().isComplex() && !selectItemPath.getLeaf().isCollection()) {
for (final JPAPath selectSubItemPath : selectItemPath.getLeaf().getStructuredType().getPathList()) {
if (pathContainsCollection(selectSubItemPath))
collectionAttributes.add(getCollection(jpaEntity, selectSubItemPath, selectItemPath.getPath().get(0)
.getExternalName()));
}
} else if (pathContainsCollection(selectItemPath)) {
collectionAttributes.add(selectItemPath);
}
}
}
return collectionAttributes;
}
private JPAPath getCollection(final JPAStructuredType jpaEntity, final JPAPath path, final String prefix)
throws ODataJPAModelException {
final StringBuilder pathAlias = new StringBuilder(prefix);
for (final JPAElement pathElement : path.getPath()) {
pathAlias.append(JPAPath.PATH_SEPARATOR);
pathAlias.append(pathElement.getExternalName());
if (pathElement instanceof final JPAAttribute attribute
&& attribute.isCollection()
&& !attribute.isTransient()) {
return jpaEntity.getPath(pathAlias.toString());
}
}
return null;
}
private boolean pathContainsCollection(final JPAPath path) {
for (final JPAElement pathElement : path.getPath()) {
if (pathElement instanceof final JPAAttribute attribute
&& attribute.isCollection()
&& !attribute.isTransient()) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANoSelectionException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANoSelectionException.java | package com.sap.olingo.jpa.processor.core.query;
/**
* The exception shall be raised in case no selection left, so it is not necessary to perform a query. <br>
* It is expected that the exception is handled internally.
*
* @author Oliver Grande
* Created: 14.07.2019
*
*/
public class JPANoSelectionException extends Exception {
private static final long serialVersionUID = -2120984389807283569L;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForExistsQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForExistsQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public class JPANavigationCountForExistsQuery extends JPANavigationCountQuery implements ExistsExpressionValue {
JPANavigationCountForExistsQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType type,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final Optional<JPAODataClaimProvider> claimsProvider,
final List<UriParameter> keyPredicates) throws ODataApplicationException {
super(odata, sd, type, em, parent, from, association, claimsProvider, keyPredicates);
}
/**
* Only in case there a more than one join columns
*
* <pre>
* SELECT E0."Number" S0, E0."ID" S1
* FROM "OLINGO"."Collections" E0
* WHERE (EXISTS(
* SELECT E2."ID" S0
* FROM "OLINGO"."Collections" E1
* INNER JOIN "OLINGO"."NestedComplex" E2
* ON ((E1."ID" = E2."ID")
* AND (E1."Number" = E2."Number"))
* WHERE ((E2."ID" = E0."ID")
* AND (E2."Number" = E0."Number"))
* GROUP BY E2."ID", E2."Number"
* HAVING (COUNT(E2."ID") = 1))) *
* </pre>
*/
@Override
protected void createSubQueryCollectionProperty() throws ODataApplicationException {
try {
final List<JPAOnConditionItem> left = association
.getJoinTable()
.getJoinColumns(); // Collections -->
createSelectClauseAggregation(subQuery, queryRoot, left, false);
Expression<Boolean> whereCondition = createWhereByAssociation(from, queryRoot, left);
whereCondition = addWhereClause(whereCondition,
createProtectionWhereForEntityType(claimsProvider, (JPAEntityType) association.getSourceType(), queryRoot));
subQuery.where(applyAdditionalFilter(whereCondition));
handleAggregation(subQuery, queryRoot, determineAggregationLeftColumns());
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* <pre>
* SELECT E2."CodePublisher" S0
* FROM "OLINGO"."AdministrativeDivision" E2
* WHERE (((E2."ParentDivisionCode" = E0."DivisionCode")
* AND (E2."ParentCodeID" = E0."CodeID"))
* AND (E2."CodePublisher" = E0."CodePublisher"))
* GROUP BY E2."CodePublisher", E2."ParentCodeID", E2."ParentDivisionCode"
* HAVING (COUNT(E2."CodePublisher") = 2)
* </pre>
*
* @param <T>
* @param childQuery
* @param query
* @throws ODataApplicationException
*/
@Override
protected <T> void createSubQueryAggregation(final Subquery<T> query)
throws ODataApplicationException {
createSelectClauseJoin(query, queryRoot, determineAggregationRightColumns(), false);
Expression<Boolean> whereCondition =
createWhereByAssociation(from, queryRoot, determineJoinColumns());
whereCondition = addWhereClause(whereCondition,
createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot));
query.where(applyAdditionalFilter(whereCondition));
handleAggregation(query, queryRoot, determineAggregationRightColumns());
}
/**
* <pre>
* select distinct E0."SourceKey" S0, E0."Number" S1
* from "OLINGO"."JoinSource" E0
* where exists ( select E2."SourceID" S0
* from "OLINGO"."JoinRelation" E2
* inner join "OLINGO"."JoinTarget" E3
* on (E2."TargetID" = E3."TargetKey")
* where (E2."SourceID" = E0."SourceKey")
* group by E2."SourceID"
* having (COUNT(E3."TargetKey") = 2))
* </pre>
*/
@Override
protected void createSubQueryJoinTableAggregation() throws ODataApplicationException {
try {
final List<JPAOnConditionItem> left = association
.getJoinTable()
.getJoinColumns(); // Person -->
final List<JPAOnConditionItem> right = association
.getJoinTable()
.getInverseJoinColumns(); // Person -->
createSelectClauseAggregation(subQuery, queryJoinTable, left, false);
Expression<Boolean> whereCondition = createWhereByAssociation(from, queryJoinTable, left);
whereCondition = addWhereClause(whereCondition, createWhereByAssociation(queryJoinTable, queryRoot, right));
whereCondition = addWhereClause(whereCondition, createProtectionWhereForEntityType(claimsProvider, jpaEntity,
queryRoot));
subQuery.where(applyAdditionalFilter(whereCondition));
createGroupBy(subQuery, queryJoinTable, left);
createHaving(subQuery);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
@Override
public List<Path<Comparable<?>>> getLeftPaths() {
return Collections.emptyList();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractExpandJoinQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractExpandJoinQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
abstract class JPAAbstractExpandJoinQuery extends JPAAbstractExpandQuery {
final Optional<JPAKeyBoundary> keyBoundary;
JPAAbstractExpandJoinQuery(final OData odata, final JPAEntityType jpaEntityType,
final JPAODataRequestContextAccess requestContext, final JPAAssociationPath association) throws ODataException {
super(odata, jpaEntityType, requestContext, association);
this.keyBoundary = Optional.empty();
}
JPAAbstractExpandJoinQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAInlineItemInfo item, final Optional<JPAKeyBoundary> keyBoundary) throws ODataException {
super(odata, requestContext, item);
this.keyBoundary = keyBoundary;
}
JPAAbstractExpandJoinQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAEntityType et, final JPAAssociationPath association, final List<JPANavigationPropertyInfo> hops,
final Optional<JPAKeyBoundary> keyBoundary)
throws ODataException {
super(odata, requestContext, et, association, hops);
this.keyBoundary = keyBoundary;
}
Expression<Boolean> createWhere() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createWhere")) {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
// Given keys: Organizations('1')/Roles(...)
whereCondition = createKeyWhere(navigationInfo);
whereCondition = addWhereClause(whereCondition, createBoundary(navigationInfo, keyBoundary));
whereCondition = addWhereClause(whereCondition, createExpandWhere());
whereCondition = addWhereClause(whereCondition, createProtectionWhere(claimsProvider));
whereCondition = addWhereClause(whereCondition, createWhereEnhancement());
return whereCondition;
}
}
List<Selection<?>> createAdditionSelectionForJoinTable(final JPAAssociationPath association)
throws ODataJPAQueryException {
final List<Selection<?>> selections = new ArrayList<>();
final From<?, ?> parent = determineParentFrom(); // e.g. JoinSource
try {
for (final JPAPath p : association.getLeftColumnsList()) {
final Path<?> selection = ExpressionUtility.convertToCriteriaPath(parent, p.getPath());
// If source and target of an association use the same name for their key we get conflicts with the alias.
// Therefore it is necessary to unify them.
selection.alias(association.getAlias() + ALIAS_SEPARATOR + p.getAlias());
selections.add(selection);
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return selections;
}
private jakarta.persistence.criteria.Expression<Boolean> createExpandWhere() throws ODataApplicationException {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
for (final JPANavigationPropertyInfo info : this.navigationInfo) {
if (info.getFilterCompiler() != null) {
try {
whereCondition = addWhereClause(whereCondition, info.getFilterCompiler().compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR,
HttpStatusCode.BAD_REQUEST, e);
}
}
}
return whereCondition;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/ExistsExpressionValue.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/ExistsExpressionValue.java | package com.sap.olingo.jpa.processor.core.query;
/**
* Tag interface to indicate that a sub query shall be used for an EXISTS expression
* @author Oliver Grande
* @since 2.0.1
* 20.11.2023
*/
public interface ExistsExpressionValue {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorCountAttribute;
/**
* A query to retrieve the expand entities.
* <p>
* According to
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398162"
* >OData Version 4.0 Part 2 - 5.1.2 System Query Option $expand</a> the following query options are allowed:
* <ul>
* <li>expandCountOption = <b>filter</b>/ search
* <p>
* <li>expandRefOption = expandCountOption/ <b>orderby</b> / <b>skip</b> / <b>top</b> / inlinecount
* <li>expandOption = expandRefOption/ <b>select</b>/ <b>expand</b> / <b>levels</b>
* <p>
* </ul>
* As of now only the bold once are supported
* <p>
* @author Oliver Grande
*
*/
public final class JPAExpandJoinQuery extends JPAAbstractExpandJoinQuery implements JPAExpandQuery {
private JPAQueryCreationResult tupleQuery;
public JPAExpandJoinQuery(final OData odata, final JPAInlineItemInfo item,
final JPAODataRequestContextAccess requestContext, final Optional<JPAKeyBoundary> keyBoundary)
throws ODataException {
super(odata, requestContext, item, keyBoundary);
}
public JPAExpandJoinQuery(final OData odata, final JPAAssociationPath association, final JPAEntityType entityType,
final JPAODataRequestContextAccess requestContext) throws ODataException {
super(odata, entityType, requestContext, association);
}
/**
* Process a expand query, which may contains a $skip and/or a $top option.
* <p>
* This is a tricky problem, as it can not be done easily with SQL. It could be that a database offers special
* solutions. There is an worth reading blog regards this topic:
* <a href="http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/">How to select
* the first/least/max row per group in SQL</a>. Often databases offer the option to use <code>ROW_NUMBER</code>
* together with <code>OVER ... ORDER BY</code> see e.g. <a
* href="http://www.sqltutorial.org/sql-window-functions/sql-row_number/">SQL ROW_NUMBER</a>.
* Unfortunately this is not supported by JPA.
* @return query result
* @throws ODataApplicationException
*/
@Override
public JPAExpandQueryResult execute() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "execute")) {
tupleQuery = createTupleQuery();
List<Tuple> intermediateResult;
try (JPARuntimeMeasurement resultMeasurement = debugger.newMeasurement(tupleQuery, "getResultList")) {
intermediateResult = tupleQuery.query().getResultList();
}
// Simplest solution for the top/skip problem. Read all and throw away, what is not requested
final Map<String, List<Tuple>> result = convertResult(intermediateResult, association, determineSkip(),
determineTop());
return new JPAExpandQueryResult(result, count(), jpaEntity, tupleQuery.selection().joinedRequested(),
skipTokenProvider);
} catch (final JPANoSelectionException e) {
return new JPAExpandQueryResult(emptyMap(), emptyMap(), this.jpaEntity, emptyList(), Optional.empty());
}
}
private long determineTop() {
if (uriResource.getTopOption() != null) {
return uriResource.getTopOption().getValue();
}
return Long.MAX_VALUE;
}
private long determineSkip() {
if (uriResource.getSkipOption() != null) {
return uriResource.getSkipOption().getValue();
}
return 0;
}
/**
* Returns the generated SQL string after the query has been executed, otherwise an empty string.<br>
* As of now this is only supported for EclipseLink
* @return
* @throws ODataJPAQueryException
*/
String getSQLString() throws ODataJPAQueryException {
if (tupleQuery != null && tupleQuery.query().getClass().getCanonicalName().equals(
"org.eclipse.persistence.internal.jpa.EJBQueryImpl")) {
try {
final Object dbQuery = tupleQuery.query().getClass().getMethod("getDatabaseQuery")
.invoke(tupleQuery.query());
return (String) dbQuery.getClass().getMethod("getSQLString").invoke(dbQuery);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
} else {
return "";
}
}
@Override
protected List<Selection<?>> createSelectClause(final Map<String, From<?, ?>> joinTables,
final Collection<JPAPath> jpaPathList,
final From<?, ?> target, final List<String> groups) throws ODataApplicationException {
final List<Selection<?>> selections = new ArrayList<>(super.createSelectClause(joinTables, jpaPathList, target,
groups));
if (association.hasJoinTable()) {
// For associations with JoinTable the join columns, linking columns to the parent, need to be added
selections.addAll(createAdditionSelectionForJoinTable(association));
}
return selections;
}
/**
* Splits up a expand results, so it is returned as a map that uses a concatenation of the field values know by the
* parent.
* @param intermediateResult
* @param associationPath
* @param skip
* @param top
* @return
* @throws ODataApplicationException
*/
Map<String, List<Tuple>> convertResult(final List<Tuple> intermediateResult, final JPAAssociationPath associationPath,
final long skip, final long top) throws ODataApplicationException {
String joinKey = "";
long skipped = 0;
long taken = 0;
List<Tuple> subResult = null;
final Map<String, List<Tuple>> convertedResult = new HashMap<>();
for (final Tuple row : intermediateResult) {
String actualKey;
try {
actualKey = buildConcatenatedKey(row, associationPath);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
if (!actualKey.equals(joinKey)) {
subResult = new ArrayList<>();
convertedResult.put(actualKey, subResult);
joinKey = actualKey;
skipped = taken = 0;
}
if (subResult != null && skipped >= skip && taken < top) {
taken += 1;
subResult.add(row);
} else {
skipped += 1;
}
}
return convertedResult;
}
@Override
final Map<String, Long> count() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "count")) {
final JPAExpandJoinCountQuery countQuery = new JPAExpandJoinCountQuery(odata, requestContext, jpaEntity,
association, navigationInfo, keyBoundary);
return countQuery.count();
} catch (final ODataException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
private JPAQueryCreationResult createTupleQuery() throws ODataApplicationException, JPANoSelectionException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createTupleQuery")) {
final var orderByAttributes = getOrderByAttributes(uriResource.getOrderByOption());
final SelectionPathInfo<JPAPath> selectionPath = buildSelectionPathList(this.uriResource);
final Map<String, From<?, ?>> joinTables = createFromClause(orderByAttributes, selectionPath.joinedPersistent(),
cq, lastInfo);
// TODO handle Join Column is ignored
cq.multiselect(createSelectClause(joinTables, selectionPath.joinedPersistent(), target, groups)).distinct(true);
final jakarta.persistence.criteria.Expression<Boolean> whereClause = createWhere();
if (whereClause != null) {
cq.where(whereClause);
}
final Set<Path<?>> orderByPaths = new HashSet<>();
final List<Order> orderBy = createOrderByJoinCondition(association);
orderBy.addAll(new JPAOrderByBuilder(jpaEntity, target, cb, groups).createOrderByList(joinTables,
orderByAttributes, lastInfo.getUriInfo()));
cq.orderBy(orderBy);
if (orderByAttributes.stream().anyMatch(attribute -> attribute.requiresJoin()
&& attribute instanceof JPAProcessorCountAttribute)) {
cq.groupBy(createGroupBy(joinTables, target, selectionPath.joinedPersistent(), orderByPaths));
}
final TypedQuery<Tuple> query = em.createQuery(cq);
return new JPAQueryCreationResult(query, selectionPath);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public abstract class JPANavigationCountQuery extends JPANavigationSubQuery {
JPANavigationCountQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType type,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final Optional<JPAODataClaimProvider> claimsProvider,
final List<UriParameter> keyPredicates) throws ODataApplicationException {
super(odata, sd, type, em, parent, from, association, claimsProvider, keyPredicates);
this.aggregationType = UriResourceKind.count;
}
/**
* Creates a exist sub query including the where clause joining this query with the parent query
*/
@Override
@SuppressWarnings("unchecked")
public <T extends Object> Subquery<T> getSubQuery(final Subquery<?> childQuery,
final VisitableExpression expression, final List<Path<Comparable<?>>> inPath) throws ODataApplicationException {
if (childQuery != null)
// A count query should be the last in a chain. Therefore childQuery has to be null
throw new ODataJPAQueryException(QUERY_PREPARATION_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR);
final Subquery<T> query = (Subquery<T>) this.subQuery;
if (this.association.getJoinTable() != null) {
if (isCollectionProperty)
createSubQueryCollectionProperty();
else
createSubQueryJoinTableAggregation();
} else {
createSubQueryAggregation(query);
}
return query;
}
protected abstract <T> void createSubQueryAggregation(final Subquery<T> query) throws ODataApplicationException;
protected abstract void createSubQueryJoinTableAggregation() throws ODataApplicationException;
protected abstract void createSubQueryCollectionProperty() throws ODataApplicationException;
protected void createHaving(final Subquery<?> subQuery) throws ODataApplicationException {
try {
subQuery.having(this.filterComplier.compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryResult.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import jakarta.persistence.Tuple;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.CardinalityValue;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollection;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
/**
* Builds a hierarchy of expand results. One instance contains on the one hand of the result itself, a map which has the
* join columns values of the parent as its key and on the other hand a map that point the results of the next expand.
* The join columns are concatenated in the order they are stored in the corresponding Association Path.
* @author Oliver Grande
*
*/
public final class JPAExpandQueryResult implements JPAExpandResult, JPAConvertibleResult {
private static final Map<String, List<Tuple>> EMPTY_RESULT;
private final Map<JPAAssociationPath, JPAExpandResult> childrenResult;
private final Map<String, List<Tuple>> jpaResult;
private final Map<String, JPAEntityCollectionExtension> odataResult;
private final Map<String, Long> counts;
private final JPAEntityType jpaEntityType;
private final Collection<JPAPath> requestedSelection;
private final Optional<JPAODataSkipTokenProvider> skipTokenProvider;
static {
EMPTY_RESULT = new HashMap<>(1);
putEmptyResult();
}
/**
* Add an empty list as result for root to the EMPTY_RESULT. This is needed, as the conversion eats up the database
* result.
* @see JPATupleChildConverter
* @return
*/
private static Map<String, List<Tuple>> putEmptyResult() {
EMPTY_RESULT.put(ROOT_RESULT_KEY, Collections.emptyList());
return EMPTY_RESULT;
}
public JPAExpandQueryResult(final JPAEntityType jpaEntityType, final Collection<JPAPath> selectionPath) {
this(putEmptyResult(), Collections.emptyMap(), jpaEntityType, selectionPath, Optional.empty());
}
public JPAExpandQueryResult(final Map<String, List<Tuple>> result, final Map<String, Long> counts,
@Nonnull final JPAEntityType jpaEntityType, final Collection<JPAPath> selectionPath,
final Optional<JPAODataSkipTokenProvider> skipTokenProvider) {
Objects.requireNonNull(jpaEntityType);
childrenResult = new HashMap<>();
this.jpaResult = result;
this.counts = counts;
this.jpaEntityType = jpaEntityType;
this.requestedSelection = selectionPath;
this.skipTokenProvider = skipTokenProvider;
this.odataResult = new HashMap<>(jpaResult.size());
}
@Override
public Map<String, JPAEntityCollectionExtension> asEntityCollection(final JPAResultConverter converter)
throws ODataApplicationException {
convert(converter, ROOT_RESULT_KEY, new ArrayList<>());
return odataResult;
}
@Override
public void convert(final JPAResultConverter converter) throws ODataApplicationException {
throw new IllegalAccessError("");
}
JPAEntityCollectionExtension convert(final JPAResultConverter converter, final String parentKey,
final List<JPAODataPageExpandInfo> expandInfo) throws ODataApplicationException {
if (!odataResult.containsKey(parentKey)) {
odataResult.put(parentKey, converter.getResult(this, requestedSelection, parentKey, expandInfo));
}
return odataResult.get(parentKey);
}
private JPAEntityCollectionExtension convertOnDemand(final JPAResultConverter converter, final String parentKey,
final List<JPAODataPageExpandInfo> expandInfo) throws ODataApplicationException {
final var result = converter.getResult(this, requestedSelection, parentKey, expandInfo);
jpaResult.put(parentKey, null);
return result;
}
private JPAEntityCollectionExtension convert(final String key, final JPAResultConverter converter,
final JPAAssociationPath association, final List<JPAODataPageExpandInfo> expandInfo)
throws ODataApplicationException {
return association.cardinality().source == CardinalityValue.ONE
? convertOnDemand(converter, key, expandInfo)
: convert(converter, key, expandInfo);
}
@Override
public JPAExpandResult getChild(final JPAAssociationPath associationPath) {
return childrenResult.get(associationPath);
}
/*
* (non-Javadoc)
*
* @see org.apache.org.jpa.processor.core.converter.JPAExpandResult#getChildren()
*/
@Override
public Map<JPAAssociationPath, JPAExpandResult> getChildren() {
return childrenResult;
}
/*
* (non-Javadoc)
*
* @see org.apache.org.jpa.processor.core.converter.JPAExpandResult#getCount()
*/
@Override
public Long getCount(final String key) {
return counts != null ? counts.get(key) : null;
}
/*
* (non-Javadoc)
*
* @see org.apache.org.jpa.processor.core.converter.JPAExpandResult#getEntityType()
*/
@Override
public JPAEntityType getEntityType() {
return jpaEntityType;
}
public long getNoResults() {
return jpaResult.size();
}
public long getNoResultsDeep() {
long count = 0;
for (final Entry<String, List<Tuple>> result : jpaResult.entrySet()) {
count += result.getValue().size();
}
return count;
}
/*
* (non-Javadoc)
*
* @see org.apache.org.jpa.processor.core.converter.JPAExpandResult#getResult(java.lang.String)
*/
@Override
public List<Tuple> getResult(final String key) {
return jpaResult.get(key);
}
@Override
public List<Tuple> removeResult(final String key) {
return jpaResult.put(key, null);
}
/*
* (non-Javadoc)
*
* @see org.apache.org.jpa.processor.core.converter.JPAExpandResult#hasCount()
*/
@Override
public boolean hasCount() {
return counts != null;
}
@Override
public void putChildren(final Map<JPAAssociationPath, JPAExpandResult> childResults)
throws ODataApplicationException {
for (final JPAAssociationPath child : childResults.keySet()) {
if (childrenResult.get(child) != null)
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_RESULT_EXPAND_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR);
}
childrenResult.putAll(childResults);
}
@Override
public Map<String, List<Tuple>> getResults() {
return jpaResult;
}
@Override
public JPAEntityCollectionExtension getEntityCollection(final String key, final JPAResultConverter converter,
final JPAAssociationPath association, final List<JPAODataPageExpandInfo> expandInfo)
throws ODataApplicationException {
return jpaResult.containsKey(key)
? convert(key, converter, association, expandInfo)
: new JPAEntityCollection();
}
@Override
public Optional<JPAKeyBoundary> getKeyBoundary(final JPAODataRequestContextAccess requestContext,
final List<JPANavigationPropertyInfo> hops) throws ODataJPAProcessException {
try {
if (!jpaResult.get(ROOT_RESULT_KEY).isEmpty()
&& (requestContext.getUriInfo().getExpandOption() != null
|| collectionPropertyRequested(requestContext))
&& (requestContext.getUriInfo().getTopOption() != null
|| requestContext.getUriInfo().getSkipOption() != null)) {
final JPAKeyPair boundary = new JPAKeyPair(jpaEntityType.getKey(), requestContext.getQueryDirectives());
for (final Tuple tuple : jpaResult.get(ROOT_RESULT_KEY)) {
@SuppressWarnings("rawtypes")
final Map<JPAAttribute, Comparable> key = createKey(tuple);
boundary.setValue(key);
}
return Optional.of(new JPAKeyBoundary(hops.size(), boundary));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return JPAConvertibleResult.super.getKeyBoundary(requestContext, hops);
}
@Override
public Collection<JPAPath> getRequestedSelection() {
return requestedSelection;
}
private boolean collectionPropertyRequested(final JPAODataRequestContextAccess requestContext)
throws ODataJPAModelException {
if (!jpaEntityType.getCollectionAttributesPath().isEmpty()) {
final SelectOption selectOptions = requestContext.getUriInfo().getSelectOption();
if (SelectOptionUtil.selectAll(selectOptions)) {
return true;
} else {
for (final SelectItem item : selectOptions.getSelectItems()) {
final String pathItem = item.getResourcePath().getUriResourceParts().stream().map(path -> (path
.getSegmentValue())).collect(Collectors.joining(JPAPath.PATH_SEPARATOR));
if (this.jpaEntityType.getCollectionAttribute(pathItem) != null) {
return true;
}
}
}
}
return false;
}
@SuppressWarnings("rawtypes")
private Map<JPAAttribute, Comparable> createKey(final Tuple tuple) throws ODataJPAModelException {
final Map<JPAAttribute, Comparable> keyMap = new HashMap<>(jpaEntityType.getKey().size());
for (final JPAAttribute key : jpaEntityType.getKey()) {
keyMap.put(key, (Comparable) tuple.get(key.getExternalName()));
}
return keyMap;
}
@Override
public String getSkipToken(final List<JPAODataPageExpandInfo> foreignKeyStack) {
return skipTokenProvider
.map(provider -> provider.get(foreignKeyStack))
.map(this::convertToken)
.orElse(null);
}
private String convertToken(final Object skipToken) {
if (skipToken instanceof final String s)
return s;
return skipToken.toString();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/EdmBoundCast.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/EdmBoundCast.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmException;
import org.apache.olingo.commons.api.edm.EdmMapping;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding;
import org.apache.olingo.commons.api.edm.EdmTerm;
class EdmBoundCast implements EdmBindingTarget {
private final EdmEntityType edmType;
private final EdmBindingTarget edmBindingTarget;
EdmBoundCast(final EdmEntityType edmType, final EdmBindingTarget edmBindingTarget) {
super();
this.edmType = edmType;
this.edmBindingTarget = edmBindingTarget;
}
@Override
public String getName() {
return edmType.getName();
}
@Override
public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) {
return edmType.getAnnotation(term, qualifier);
}
@Override
public List<EdmAnnotation> getAnnotations() {
return edmType.getAnnotations();
}
@Override
public EdmMapping getMapping() {
return null;
}
@Override
public String getTitle() {
return null;
}
@Override
public EdmBindingTarget getRelatedBindingTarget(final String path) {
final EdmNavigationProperty navigation = edmType.getNavigationProperty(path);
if (navigation == null)
throw new EdmException("Unknown navigation property with name: " + path);
final EdmEntityType targetEntityType = navigation.getType();
if (targetEntityType == null)
throw new EdmException("Target entity type not found of navigation property with name: " + path);
return new EdmBoundCast(targetEntityType, this);
}
@Override
public List<EdmNavigationPropertyBinding> getNavigationPropertyBindings() {
return Collections.emptyList();
}
@Override
public EdmEntityContainer getEntityContainer() {
return edmBindingTarget.getEntityContainer();
}
@Override
public EdmEntityType getEntityType() {
return edmType;
}
@Override
public EdmEntityType getEntityTypeWithAnnotations() {
return null;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/Utility.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/Utility.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath.PATH_SEPARATOR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.NOT_SUPPORTED_RESOURCE_TYPE;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAUtilException.MessageKeys.UNKNOWN_ENTITY_TYPE;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAUtilException.MessageKeys.UNKNOWN_NAVI_PROPERTY;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.NOT_IMPLEMENTED;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nonnull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceLambdaVariable;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.UriResourceSingleton;
import org.apache.olingo.server.api.uri.UriResourceValue;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAUtilException;
import com.sap.olingo.jpa.processor.core.uri.JPAUriResourceNavigationImpl;
public final class Utility {
public static final String VALUE_RESOURCE = "$VALUE";
private static final String FOUND_CAST_FROM = "Found cast from ";
private static final Log LOGGER = LogFactory.getLog(Utility.class);
private Utility() {
// suppress instance creation
}
public static JPAAssociationPath determineAssociation(final JPAServiceDocument sd, final EdmType navigationStart,
final StringBuilder associationName) throws ODataApplicationException {
try {
final JPAEntityType navigationStartType = sd.getEntity(navigationStart);
if (navigationStartType == null)
throw new ODataJPAUtilException(UNKNOWN_ENTITY_TYPE, BAD_REQUEST);
JPAAssociationPath path = navigationStartType.getAssociationPath(associationName.toString());
if (path == null) {
final var collection = navigationStartType.getCollectionAttribute(associationName.toString());
if (collection != null)
path = collection.asAssociation();
}
return path;
} catch (final ODataJPAModelException e) {
throw new ODataJPAUtilException(UNKNOWN_NAVI_PROPERTY, BAD_REQUEST, e);
}
}
public static JPAAssociationPath determineAssociationPath(final JPAServiceDocument sd,
final UriResourcePartTyped navigationStart, final StringBuilder associationName)
throws ODataApplicationException {
JPAEntityType navigationStartType = null;
try {
if (navigationStart instanceof final UriResourceEntitySet entitySet) {
if (entitySet.getTypeFilterOnEntry() != null)
navigationStartType = sd.getEntity(entitySet.getTypeFilterOnEntry());
else if (entitySet.getTypeFilterOnCollection() != null)
navigationStartType = sd.getEntity(entitySet.getTypeFilterOnCollection());
else
navigationStartType = sd.getEntity(entitySet.getType());
}
if (navigationStart instanceof final UriResourceSingleton singleton) {
navigationStartType = sd.getEntity(singleton.getType());
} else if (navigationStart instanceof final UriResourceNavigation navigation) {
if (navigation.getTypeFilterOnEntry() != null)
navigationStartType = sd.getEntity(navigation.getTypeFilterOnEntry());
else
navigationStartType = sd.getEntity(navigation.getProperty().getType());
}
JPAAssociationPath path = navigationStartType == null ? null : navigationStartType.getAssociationPath(
associationName.toString());
if (path == null && navigationStartType != null) {
final JPACollectionAttribute collection = navigationStartType.getCollectionAttribute(associationName
.toString());
if (collection != null)
path = collection.asAssociation();
}
return path;
} catch (final ODataJPAModelException e) {
throw new ODataJPAUtilException(UNKNOWN_NAVI_PROPERTY, BAD_REQUEST, e);
}
}
public static Map<JPAExpandItem, JPAAssociationPath> determineAssociations(final JPAServiceDocument sd,
final List<UriResource> startResourceList, final ExpandOption expandOption) throws ODataApplicationException {
final Map<JPAExpandItem, JPAAssociationPath> pathList = new HashMap<>();
final StringBuilder associationNamePrefix = new StringBuilder();
if (startResourceList != null && expandOption != null) {
final UriResource startResourceItem = createAssociationNamePrefix(startResourceList, associationNamePrefix);
// Example1 : ?$expand=Created/User (Property/NavigationProperty)
// Example2 : ?$expand=Parent/CodeID (NavigationProperty/Property)
// Example3 : ?$expand=Parent,Children (NavigationProperty, NavigationProperty)
// Example4 : ?$expand=*
// Example5 : ?$expand=*/$ref,Parent
// Example6 : ?$expand=Parent($levels=2)
// Example7 : ?$expand=*($levels=2)
// Example8 : ?$expand=*($levels=2;$expand=Parent)
// Example9 : ?$expand=BusinessPartner/com.sap.olingo.jpa.Person
for (final ExpandItem item : expandOption.getExpandItems()) {
if (item.isStar()) {
determineAssociationsStar(sd, startResourceList, expandOption, pathList, associationNamePrefix, item);
} else {
determineAssociations(sd, expandOption, pathList, associationNamePrefix, Objects.requireNonNull(
startResourceItem), item);
// For example8 Olingo only provides one ExpandItem next level has to expand Parent
}
if (item.getLevelsOption() != null && item.getLevelsOption().isMax())
LOGGER.warn(
"Client requested expand with $levels=max. This is depricated. The support will be stop in the future");
}
}
return pathList;
}
public static Map<JPAPath, JPAAssociationPath> determineAssociations(final JPAServiceDocument sd,
final List<UriResource> startResourceList, final Set<JPAPath> selectOptions) throws ODataApplicationException {
final Map<JPAPath, JPAAssociationPath> pathList = new HashMap<>();
final StringBuilder associationNamePrefix = new StringBuilder();
final UriResource startResourceItem = createAssociationNamePrefix(startResourceList, associationNamePrefix);
for (final var selectOption : selectOptions) {
final StringBuilder associationName = !associationNamePrefix.isEmpty()
? new StringBuilder(associationNamePrefix).append(selectOption.getAlias())
: new StringBuilder(selectOption.getAlias());
pathList.put(selectOption, determineAssociationPath(sd, (UriResourcePartTyped) startResourceItem,
associationName));
}
return pathList;
}
private static UriResource createAssociationNamePrefix(final List<UriResource> startResourceList,
final StringBuilder associationNamePrefix) {
// Example1: /Organizations('3')/AdministrativeInformation?$expand=Created/User
// Example2: /Organizations('3')/AdministrativeInformation?$expand=*
// Example3: /CurrentUser/AdministrativeInformation?$expand=Created/User
// Association name needs AdministrativeInformation as prefix
UriResource startResourceItem = null;
for (int i = startResourceList.size() - 1; i >= 0; i--) {
startResourceItem = startResourceList.get(i);
if (startResourceItem instanceof UriResourceEntitySet
|| startResourceItem instanceof UriResourceNavigation
|| startResourceItem instanceof UriResourceSingleton) {
break;
}
associationNamePrefix.insert(0, PATH_SEPARATOR);
associationNamePrefix.insert(0, ((UriResourceProperty) startResourceItem).getProperty().getName());
}
return startResourceItem;
}
private static void determineAssociations(final JPAServiceDocument sd, final ExpandOption expandOption,
final Map<JPAExpandItem, JPAAssociationPath> pathList, final StringBuilder associationNamePrefix,
final UriResource startResourceItem, final ExpandItem item) throws ODataApplicationException {
final List<UriResource> targetResourceList = item.getResourcePath().getUriResourceParts(); // Has Cast
final StringBuilder associationName = determinePathAlias(associationNamePrefix, targetResourceList);
if (item.getLevelsOption() != null)
pathList.put(new JPAExpandLevelWrapper(sd, expandOption, item), Utility.determineAssociation(sd,
((UriResourcePartTyped) startResourceItem).getType(), associationName));
else
pathList.put(new JPAExpandItemWrapper(sd, item), Utility.determineAssociation(sd,
((UriResourcePartTyped) startResourceItem).getType(), associationName));
}
private static StringBuilder determinePathAlias(final StringBuilder pathAliasPrefix,
final List<UriResource> resourceList) {
StringBuilder associationName;
associationName = new StringBuilder();
associationName.append(pathAliasPrefix);
for (final var targetResourceItem : resourceList) {
if (targetResourceItem.getKind() == UriResourceKind.entitySet
|| targetResourceItem.getKind() == UriResourceKind.singleton)
continue;
if (targetResourceItem.getKind() != UriResourceKind.navigationProperty) {
associationName.append(((UriResourceProperty) targetResourceItem).getProperty().getName());
associationName.append(PATH_SEPARATOR);
} else {
associationName.append(((UriResourceNavigation) targetResourceItem).getProperty().getName());
break;
}
}
return associationName;
}
private static void determineAssociationsStar(final JPAServiceDocument sd, final List<UriResource> startResourceList,
final ExpandOption expandOption, final Map<JPAExpandItem, JPAAssociationPath> pathList,
final StringBuilder associationNamePrefix, final ExpandItem item) throws ODataJPAUtilException {
try {
// As olingo does not resolve the Star operator the expand item does not contain a resource path
final EdmStructuredType edmNavigationStart = determineNavigationStartForStar(startResourceList);
determineAssociationsStar(sd, expandOption, pathList, associationNamePrefix, item, edmNavigationStart);
} catch (final ODataJPAModelException e) {
throw new ODataJPAUtilException(UNKNOWN_ENTITY_TYPE, BAD_REQUEST, e);
}
}
private static EdmEntityType determineNavigationStartForStar(final List<UriResource> resources) {
EdmEntityType result = null;
for (final UriResource resourceItem : resources) {
if (resourceItem.getKind() == UriResourceKind.entitySet) {
result = ((UriResourceEntitySet) resourceItem).getEntityType();
}
if (resourceItem.getKind() == UriResourceKind.singleton) {
result = ((UriResourceSingleton) resourceItem).getEntityType();
}
if (resourceItem.getKind() == UriResourceKind.navigationProperty) {
result = (EdmEntityType) ((UriResourceNavigation) resourceItem).getType();
}
}
return result;
}
private static void determineAssociationsStar(final JPAServiceDocument sd, final ExpandOption expandOption,
final Map<JPAExpandItem, JPAAssociationPath> pathList, final StringBuilder associationNamePrefix,
final ExpandItem item, final EdmStructuredType edmEntityType)
throws ODataJPAModelException, ODataJPAUtilException {
final JPAStructuredType jpaStructuredType = sd.getEntity(edmEntityType);
if (jpaStructuredType == null)
throw new ODataJPAUtilException(UNKNOWN_ENTITY_TYPE, BAD_REQUEST, edmEntityType.getName());
for (final JPAAssociationPath path : jpaStructuredType.getAssociationPathList()) {
if (associationNamePrefix.isEmpty() ||
path.getAlias().startsWith(associationNamePrefix.toString())) {
final var uriInfo = new JPAUriResourceNavigationImpl(findNavigationProperty(edmEntityType, path));
if (item.getLevelsOption() != null && path.getSourceType() == path.getTargetType())
pathList.put(new JPAExpandLevelWrapper(expandOption, (JPAEntityType) path.getTargetType(),
findNavigationProperty(edmEntityType, path), item), path);
else
pathList.put(new JPAExpandItemWrapper(item, (JPAEntityType) path.getTargetType(), uriInfo), path);
}
}
}
public static EdmBindingTarget determineBindingTarget(final List<UriResource> resources) {
return determineBindingTargetAndKeys(resources).getEdmBindingTarget();
}
public static EdmBindingTargetInfo determineBindingTargetAndKeys(final List<UriResource> resources) {
EdmBindingTarget targetEdmBindingTarget = null;
List<UriParameter> targetKeyPredicates = new ArrayList<>();
StringBuilder navigationPropertyName = new StringBuilder();
for (final UriResource resourceItem : resources) {
if (resourceItem.getKind() == UriResourceKind.entitySet) {
targetEdmBindingTarget = determineBindingTargetOfEntitySet((UriResourceEntitySet) resourceItem);
targetKeyPredicates = ((UriResourceEntitySet) resourceItem).getKeyPredicates();
}
if (resourceItem.getKind() == UriResourceKind.singleton) {
targetEdmBindingTarget = determineBindingTargetOfSingleton((UriResourceSingleton) resourceItem);
targetKeyPredicates = Collections.emptyList();
}
if (resourceItem.getKind() == UriResourceKind.complexProperty) {
navigationPropertyName.append(((UriResourceComplexProperty) resourceItem).getProperty().getName());
navigationPropertyName.append(PATH_SEPARATOR);
}
if (resourceItem.getKind() == UriResourceKind.navigationProperty) {
navigationPropertyName.append(((UriResourceNavigation) resourceItem).getProperty().getName());
targetKeyPredicates = ((UriResourceNavigation) resourceItem).getKeyPredicates();
final EdmBindingTarget edmBindingTarget = determineBindingTargetOfNavigation(targetEdmBindingTarget,
(UriResourceNavigation) resourceItem, navigationPropertyName);
if (edmBindingTarget instanceof EdmEntitySet || edmBindingTarget instanceof EdmBoundCast)
targetEdmBindingTarget = edmBindingTarget;
navigationPropertyName = new StringBuilder();
}
}
return new EdmBindingTargetResult(targetEdmBindingTarget, targetKeyPredicates, navigationPropertyName.toString());
}
private static EdmBindingTarget determineBindingTargetOfNavigation(final EdmBindingTarget targetEdmBindingTarget,
final UriResourceNavigation resourceItem, final StringBuilder navigationPropertyName) {
final EdmBindingTarget target = targetEdmBindingTarget.getRelatedBindingTarget(navigationPropertyName
.toString());
if (target instanceof EdmBindingTarget) {
if (resourceItem.getTypeFilterOnEntry() != null)
return new EdmBoundCast((EdmEntityType) resourceItem.getTypeFilterOnEntry(), target);
else if (resourceItem.getTypeFilterOnCollection() != null)
return new EdmBoundCast((EdmEntityType) resourceItem.getTypeFilterOnCollection(), target);
}
return target;
}
public static List<UriParameter> determineKeyPredicates(final UriResource uriResourceItem)
throws ODataApplicationException {
if (uriResourceItem instanceof final UriResourceEntitySet entiySet)
return entiySet.getKeyPredicates();
else if (uriResourceItem instanceof final UriResourceNavigation navigation)
return navigation.getKeyPredicates();
else if (uriResourceItem instanceof UriResourceSingleton)
return Collections.emptyList();
else
throw new ODataJPAQueryException(NOT_SUPPORTED_RESOURCE_TYPE, BAD_REQUEST, uriResourceItem.getKind().name());
}
public static EdmBindingTargetInfo determineModifyEntitySetAndKeys(@Nonnull final List<UriResource> resources) {
EdmBindingTarget targetEdmTopLevel = null;
List<UriParameter> targetKeyPredicates = new ArrayList<>();
StringBuilder navigationPropertyName = new StringBuilder();
for (final UriResource resourceItem : resources) {
if (resourceItem.getKind() == UriResourceKind.entitySet) {
targetEdmTopLevel = ((UriResourceEntitySet) resourceItem).getEntitySet();
targetKeyPredicates = ((UriResourceEntitySet) resourceItem).getKeyPredicates();
}
if (resourceItem.getKind() == UriResourceKind.singleton) {
targetEdmTopLevel = ((UriResourceSingleton) resourceItem).getSingleton();
}
if (resourceItem.getKind() == UriResourceKind.complexProperty) {
navigationPropertyName.append(((UriResourceComplexProperty) resourceItem).getProperty().getName());
navigationPropertyName.append(PATH_SEPARATOR);
}
if (resourceItem.getKind() == UriResourceKind.navigationProperty) {
navigationPropertyName.append(((UriResourceNavigation) resourceItem).getProperty().getName());
final List<UriParameter> keyPredicates = ((UriResourceNavigation) resourceItem).getKeyPredicates();
if (!keyPredicates.isEmpty()) {
targetKeyPredicates = keyPredicates;
final EdmBindingTarget edmBindingTarget = targetEdmTopLevel.getRelatedBindingTarget(navigationPropertyName
.toString());
if (edmBindingTarget instanceof EdmEntitySet)
targetEdmTopLevel = edmBindingTarget;
navigationPropertyName = new StringBuilder();
}
}
}
return new EdmBindingTargetResult(targetEdmTopLevel, targetKeyPredicates, navigationPropertyName.toString());
}
/**
* Converts the OData navigation list into a intermediate one. Direction is top - down usage e.g. join query.
* <p>
* The method only supports queries that start with an entity set or singleton.
*
* @param sd
* @param resourceParts
* @param filterOption
* @return
* @throws ODataApplicationException
*/
public static List<JPANavigationPropertyInfo> determineNavigationPath(final JPAServiceDocument sd,
final List<UriResource> resourceParts, final UriInfoResource uriInfo) throws ODataApplicationException {
final List<JPANavigationPropertyInfo> pathList = new ArrayList<>();
StringBuilder associationName = null;
UriResourcePartTyped source = null;
for (final UriResource resourcePart : resourceParts) {
if (resourcePart instanceof UriResourceNavigation
|| resourcePart instanceof UriResourceEntitySet
|| resourcePart instanceof UriResourceSingleton) {
if (source != null) {
if (resourcePart instanceof final UriResourceNavigation navigation)
extendNavigationPath(associationName, navigation.getProperty().getName());
pathList.add(new JPANavigationPropertyInfo(sd, source, determineAssociationPath(sd, source, associationName),
null));
}
source = (UriResourcePartTyped) resourcePart;
associationName = new StringBuilder();
} else {
if ((resourcePart instanceof UriResourceComplexProperty
|| resourcePart instanceof final UriResourceProperty property && property.isCollection())
&& associationName != null) {
extendNavigationPath(associationName, ((UriResourceProperty) resourcePart).getProperty().getName());
}
}
}
if (source != null)
pathList.add(new JPANavigationPropertyInfo(sd, source,
determineAssociationPath(sd, source, associationName), uriInfo));
return pathList;
}
public static String determinePropertyNavigationPath(final List<UriResource> resources) {
final StringBuilder pathName = new StringBuilder();
if (resources != null) {
for (int i = resources.size() - 1; i >= 0; i--) {
final UriResource resourceItem = resources.get(i);
if (resourceItem instanceof UriResourceEntitySet || resourceItem instanceof UriResourceNavigation
|| resourceItem instanceof UriResourceLambdaVariable)
break;
if (resourceItem instanceof UriResourceValue) {
pathName.insert(0, VALUE_RESOURCE);
pathName.insert(0, PATH_SEPARATOR);
} else if (resourceItem instanceof final UriResourceProperty property) {
pathName.insert(0, property.getProperty().getName());
pathName.insert(0, PATH_SEPARATOR);
}
}
if (!pathName.isEmpty())
pathName.deleteCharAt(0);
}
return pathName.toString();
}
public static String determinePropertyNavigationPrefix(final List<UriResource> resources) {
return Utility.determinePropertyNavigationPath(resources).split("/\\" + Utility.VALUE_RESOURCE)[0];
}
/**
* Finds the index of the first property after the last entity set or navigation resource. This is the resource that
* will be returned in case a complex or primitive type is requested.
* <p>
* Example1 : /Organizations -> -1<br>
* Example2 : /Organizations('3')/AdministrativeInformation -> 1<br>
* Example3 : /Organizations('3')/Roles -> -1<br>
* Example4 : /Organizations('3')/Roles/RoleCategory -> 2<br>
* Example5 : /Organizations('3')/AdministrativeInformation/Created/User/LastName -> 4
* Example6 : /CurrentUser/AdministrativeInformation -> 1
*/
public static int determineStartNavigationIndex(final List<UriResource> resources) {
if (resources != null) {
for (int i = resources.size() - 1; i >= 0; i--) {
final UriResource resourceItem = resources.get(i);
if (resourceItem instanceof UriResourceEntitySet
|| resourceItem instanceof UriResourceNavigation
|| resourceItem instanceof UriResourceSingleton)
return i == resources.size() ? -1 : i + 1;
}
}
return -1;
}
/**
* Used for Serializer
*/
public static UriResourceProperty determineStartNavigationPath(final List<UriResource> resources) {
final int index = determineStartNavigationIndex(resources);
if (index >= 0 && resources != null)
return (UriResourceProperty) resources.get(index);
return null;
}
/**
* Finds an entity type from a navigation property
*/
public static EdmEntityType determineTargetEntityType(final List<UriResource> resources) {
EdmEntityType targetEdmEntity = null;
for (final UriResource resourceItem : resources) {
if (resourceItem.getKind() == UriResourceKind.navigationProperty) {
// first try the simple way like in the example
targetEdmEntity = (EdmEntityType) ((UriResourceNavigation) resourceItem).getType();
if (((UriResourceNavigation) resourceItem).getTypeFilterOnEntry() != null) {
targetEdmEntity = (EdmEntityType) ((UriResourceNavigation) resourceItem).getTypeFilterOnEntry();
LOGGER.trace(FOUND_CAST_FROM + ((UriResourceNavigation) resourceItem).getType().getName() + " to "
+ targetEdmEntity.getName());
}
if (((UriResourceNavigation) resourceItem).getTypeFilterOnCollection() != null) {
targetEdmEntity = (EdmEntityType) ((UriResourceNavigation) resourceItem).getTypeFilterOnCollection();
LOGGER.trace(FOUND_CAST_FROM + ((UriResourceNavigation) resourceItem).getType().getName() + " to "
+ targetEdmEntity.getName());
}
}
}
return targetEdmEntity;
}
public static boolean hasNavigation(final List<UriResource> uriResourceParts) {
if (uriResourceParts != null) {
for (int i = uriResourceParts.size() - 1; i >= 0; i--) {
if (uriResourceParts.get(i) instanceof UriResourceNavigation)
return true;
}
}
return false;
}
public static boolean hasCollection(final List<UriResource> resourceParts) {
if (resourceParts != null) {
for (int i = resourceParts.size() - 1; i >= 0; i--) {
if (isCollection(resourceParts.get(i)))
return true;
}
}
return false;
}
public static boolean isCollection(final UriResource resourcePart) {
return (resourcePart instanceof final UriResourceProperty resourceProperty && resourceProperty.isCollection());
}
private static EdmBindingTarget determineBindingTargetOfEntitySet(final UriResourceEntitySet resourceItem) {
EdmBindingTarget targetEdmBindingTarget;
if (resourceItem.getTypeFilterOnCollection() != null) {
targetEdmBindingTarget = new EdmBoundCast((EdmEntityType) resourceItem.getTypeFilterOnCollection(), resourceItem
.getEntitySet());
LOGGER.trace(FOUND_CAST_FROM + resourceItem.getEntitySet().getName() + " to "
+ targetEdmBindingTarget.getName());
} else if (resourceItem.getTypeFilterOnEntry() != null) {
targetEdmBindingTarget = new EdmBoundCast((EdmEntityType) resourceItem.getTypeFilterOnEntry(), resourceItem
.getEntitySet());
LOGGER.trace(FOUND_CAST_FROM + resourceItem.getEntitySet().getName() + " to "
+ targetEdmBindingTarget.getName());
} else {
targetEdmBindingTarget = resourceItem.getEntitySet();
}
return targetEdmBindingTarget;
}
private static EdmBindingTarget determineBindingTargetOfSingleton(final UriResourceSingleton resourceItem) {
EdmBindingTarget targetEdmBindingTarget;
if (resourceItem.getEntityTypeFilter() != null) {
targetEdmBindingTarget = new EdmBoundCast(resourceItem.getEntityTypeFilter(), resourceItem.getSingleton());
} else {
targetEdmBindingTarget = resourceItem.getSingleton();
}
return targetEdmBindingTarget;
}
private static void extendNavigationPath(final StringBuilder associationName, final String pathSegment)
throws ODataJPAQueryException {
if (associationName == null)
throw new ODataJPAQueryException(NOT_SUPPORTED_RESOURCE_TYPE, NOT_IMPLEMENTED, "");
if (!associationName.isEmpty())
associationName.append(PATH_SEPARATOR);
associationName.append(pathSegment);
}
private static EdmNavigationProperty findNavigationProperty(final EdmStructuredType edmEntityType,
final JPAAssociationPath path) {
EdmStructuredType type = edmEntityType;
final var last = path.getLeaf();
for (final var item : path.getPath()) {
if (item == last)
return type.getNavigationProperty(item.getExternalName());
else
type = (EdmStructuredType) type.getProperty(item.getExternalName()).getType();
}
return type.getNavigationProperty(path.getAlias());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAQuery.java | package com.sap.olingo.jpa.processor.core.query;
import org.apache.olingo.server.api.ODataApplicationException;
public interface JPAQuery {
JPAConvertibleResult execute() throws ODataApplicationException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAStandardExtension.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAStandardExtension.java | package com.sap.olingo.jpa.processor.core.query;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
public class JPAStandardExtension implements JPAExtension {
@Override
public JPAExpandResult executeExpandTopSkipQuery() {
return null;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandCountQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandCountQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Map;
import org.apache.olingo.server.api.ODataApplicationException;
/**
*
* @author Oliver Grande
* @since 2.2.0
* 2024-08-25
*
*/
public interface JPAExpandCountQuery {
Map<String, Long> count() throws ODataApplicationException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractJoinQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractJoinQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ATTRIBUTE_NOT_FOUND;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_INVALID_SELECTION_PATH;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_RESULT_ENTITY_TYPE_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_RESULT_KEY_PROPERTY_ERROR;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.AbstractQuery;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntitySet;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterComplier;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterCrossComplier;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterRestrictionsWatchDog;
import com.sap.olingo.jpa.processor.core.filter.JPAOperationConverter;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
public abstract class JPAAbstractJoinQuery extends JPAAbstractQuery {
protected static final String ALIAS_SEPARATOR = ".";
protected final UriInfoResource uriResource;
protected final CriteriaQuery<Tuple> cq;
protected final List<JPANavigationPropertyInfo> navigationInfo;
protected final JPANavigationPropertyInfo lastInfo;
protected final JPAODataRequestContextAccess requestContext;
protected Root<?> root; // Start of a navigation
protected From<?, ?> target; // The entity that shall be returned by the query
protected Optional<JPAEntitySet> entitySet;
JPAAbstractJoinQuery(final OData odata, final JPAEntityType jpaEntityType,
final JPAODataRequestContextAccess requestContext, final List<JPANavigationPropertyInfo> navigationInfo)
throws ODataException {
this(odata, jpaEntityType, requestContext.getUriInfo(), requestContext, navigationInfo);
}
JPAAbstractJoinQuery(final OData odata, final JPAEntityType jpaEntityType, final UriInfoResource uriInfo,
final JPAODataRequestContextAccess requestContext, final List<JPANavigationPropertyInfo> navigationInfo)
throws ODataException {
super(odata, jpaEntityType, requestContext);
this.requestContext = requestContext;
this.locale = requestContext.getLocale();
this.uriResource = uriInfo;
this.cq = cb.createTupleQuery();
this.navigationInfo = navigationInfo;
this.lastInfo = determineLastInfo(navigationInfo);
this.entitySet = Optional.empty();
}
protected static Optional<JPAEntitySet> determineTargetEntitySet(final JPAODataRequestContextAccess requestContext)
throws ODataException {
final EdmBindingTarget bindingTarget = Utility.determineBindingTarget(requestContext.getUriInfo()
.getUriResourceParts());
if (bindingTarget instanceof EdmEntitySet)
return requestContext.getEdmProvider().getServiceDocument().getEntitySet(bindingTarget.getName());
return Optional.empty();
}
@SuppressWarnings("unchecked")
@Override
public <T> AbstractQuery<T> getQuery() {
return (AbstractQuery<T>) cq;
}
@SuppressWarnings("unchecked")
@Override
public <S, T> From<S, T> getRoot() {
return (From<S, T>) target;
}
/**
* Applies the $skip and $top options of the OData request to the query. The values are defined as follows:
* <ul>
* <li>The $top system query option specifies a non-negative integer n that limits the number of items returned from
* a collection.
* <li>The $skip system query option specifies a non-negative integer n that excludes the first n items of the
* queried collection from the result.
* </ul>
* These values can be restricted by a page provided by server driven paging
* <p>
* For details see:
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398306"
* >OData Version 4.0 Part 1 - 11.2.5.3 System Query Option $top</a> and
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Server-Driven_Paging"
* >OData Version 4.0 Part 1 - 11.2.5.7 Server-Driven Paging</a>
*
* @throws ODataApplicationException
*/
protected void addTopSkip(final TypedQuery<Tuple> typedQuery) {
/*
* Where $top and $skip are used together, $skip MUST be applied before $top, regardless of the order in which they
* appear in the request.
* If no unique ordering is imposed through an $orderby query option, the service MUST impose a stable ordering
* across requests that include $skip.
*
* URL example: http://localhost:8080/BuPa/BuPa.svc/Organizations?$count=true&$skip=5
*/
addTop(typedQuery);
addSkip(typedQuery);
}
protected List<JPAPath> buildEntityPathList(final JPAEntityType jpaEntity) throws ODataApplicationException {
try {
return jpaEntity.getPathList();
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, BAD_REQUEST);
}
}
protected final SelectionPathInfo<JPAPath> buildSelectionAddNavigationAndSelect(final UriInfoResource uriResource,
final SelectOption select, final SelectionPathInfo<JPAPath> jpaPathList) throws ODataApplicationException,
ODataJPAModelException {
final boolean targetIsCollection = determineTargetIsCollection(uriResource);
final String pathPrefix = Utility.determinePropertyNavigationPrefix(uriResource.getUriResourceParts());
if (Utility.VALUE_RESOURCE.equals(pathPrefix))
jpaPathList.getODataSelections().addAll(buildPathValue(jpaEntity));
else if (select == null || select.getSelectItems().isEmpty() || select.getSelectItems().get(0).isStar()) {
if (pathPrefix == null || pathPrefix.isEmpty())
copySelectableProperties(jpaPathList, buildEntityPathList(jpaEntity));
else {
expandPath(jpaEntity, jpaPathList, pathPrefix, targetIsCollection);
}
} else {
convertSelectIntoPath(select, jpaPathList, targetIsCollection, pathPrefix);
}
return jpaPathList;
}
/**
* Creates the path to all properties that need to be selected from the database. A Property can be included for the
* following reasons:
* <ul>
* <li>It is a key in order to be able to build the links</li>
* <li>It is part of the $select system query option</li>
* <li>It is the result of a navigation, which my be restricted by a $select</li>
* <li>If is required to link $expand with result with the parent result</li>
* <li>A stream is requested and the property contains the mime type</>
* </ul>
* Not included are collection properties.
*
* @param uriResource
* @return
* @throws ODataApplicationException
*/
protected SelectionPathInfo<JPAPath> buildSelectionPathList(final UriInfoResource uriResource)
throws ODataApplicationException {
// TODO It is also possible to request all actions or functions available for each returned entity:
// http://host/service/Products?$select=DemoService.*
try {
final SelectOption select = uriResource.getSelectOption();
final SelectionPathInfo<JPAPath> jpaPathList = new SelectionPathInfo<>();
buildSelectionAddNavigationAndSelect(uriResource, select, jpaPathList);
buildSelectionAddMimeType(jpaEntity, jpaPathList.getODataSelections());
buildSelectionAddKeys(jpaEntity, jpaPathList.getODataSelections());
buildSelectionAddExpandSelection(uriResource, jpaPathList.getODataSelections());
buildSelectionAddETag(jpaEntity, jpaPathList.getODataSelections());
return jpaPathList;
} catch (final ODataJPAModelException e) {
throw new ODataApplicationException(e.getLocalizedMessage(), INTERNAL_SERVER_ERROR
.getStatusCode(), ODataJPAException.getLocales().nextElement(), e);
}
}
protected <Y extends Comparable<? super Y>> jakarta.persistence.criteria.Expression<Boolean> createBoundary(
final List<JPANavigationPropertyInfo> info, final Optional<JPAKeyBoundary> keyBoundary)
throws ODataJPAQueryException {
if (keyBoundary.isPresent()) {
// Given key: Organizations('1')/Roles(...)
// First is the root
final JPANavigationPropertyInfo propertyInfo = info.get(keyBoundary.get().getNoHops() - 1);
try {
final JPAEntityType et = propertyInfo.getEntityType();
final From<?, ?> from = propertyInfo.getFromClause();
if (keyBoundary.get().getKeyBoundary().hasUpperBoundary()) {
return createBoundaryWithUpper(et, from, keyBoundary.get().getKeyBoundary());
} else {
return createBoundaryEquals(et, from, keyBoundary.get().getKeyBoundary());
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
return null;
}
protected Map<String, From<?, ?>> createFromClause(final List<JPAProcessorAttribute> orderByTarget,
final Collection<JPAPath> selectionPath, final CriteriaQuery<?> query, final JPANavigationPropertyInfo lastInfo)
throws ODataApplicationException, JPANoSelectionException {
final Map<String, From<?, ?>> joinTables = new HashMap<>();
// 1. Create navigation joins
createFromClauseRoot(query, joinTables);
target = root;
createFromClauseNavigationJoins(joinTables);
createFromClauseCollectionsJoins(joinTables);
// 2. OrderBy navigation property
createFromClauseOrderBy(orderByTarget, joinTables, target);
// 3. Description Join determine
createFromClauseDescriptionFields(selectionPath, joinTables, target, navigationInfo);
// 4. Collection Attribute Joins
generateCollectionAttributeJoin(joinTables, selectionPath, lastInfo);
return joinTables;
}
protected jakarta.persistence.criteria.Expression<Boolean> createProtectionWhere(
final Optional<JPAODataClaimProvider> claimsProvider) throws ODataJPAQueryException {
jakarta.persistence.criteria.Expression<Boolean> restriction = null;
for (final JPANavigationPropertyInfo navigation : navigationInfo) { // for all participating entity types/tables
try {
final JPAEntityType et = navigation.getEntityType();
final From<?, ?> from = navigation.getFromClause();
restriction = addWhereClause(restriction, createProtectionWhereForEntityType(claimsProvider, et, from));
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(QUERY_RESULT_ENTITY_TYPE_ERROR, INTERNAL_SERVER_ERROR, e);
}
}
return restriction;
}
protected jakarta.persistence.criteria.Expression<Boolean> createWhere(final UriInfoResource uriInfo,
final List<JPANavigationPropertyInfo> navigationInfo) throws ODataApplicationException {
try (JPARuntimeMeasurement serializerMeasurement = debugger.newMeasurement(this, "createWhere")) {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
// Given keys: Organizations('1')/Roles(...)
whereCondition = createKeyWhere(navigationInfo);
// http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301
// http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398094
// https://tools.oasis-open.org/version-control/browse/wsvn/odata/trunk/spec/ABNF/odata-abnf-construction-rules.txt
try {
final JPAFilterComplier compiler = navigationInfo.get(navigationInfo.size() - 1).getFilterCompiler();
final Expression<Boolean> filter = compiler.compile();
final Optional<JPAFilterRestrictionsWatchDog> watchDog = compiler.getWatchDog();
if (watchDog.isPresent()) {
watchDog.get().watch(filter);
}
whereCondition = addWhereClause(whereCondition, filter);
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR,
HttpStatusCode.BAD_REQUEST, e);
}
if (uriInfo.getSearchOption() != null && uriInfo.getSearchOption().getSearchExpression() != null)
whereCondition = addWhereClause(whereCondition,
requestContext.getDatabaseProcessor().createSearchWhereClause(cb, this.cq, target, jpaEntity, uriInfo
.getSearchOption()));
whereCondition = addWhereClause(whereCondition, createWhereEnhancement());
return whereCondition;
}
}
protected Expression<Boolean> createWhereEnhancement() throws ODataJPAProcessorException {
return createWhereEnhancement(jpaEntity, target);
}
@Override
protected Expression<Boolean> createWhereEnhancement(final JPAEntityType et, final From<?, ?> from)
throws ODataJPAProcessorException {
final Optional<EdmQueryExtensionProvider> queryEnhancement = requestContext.getQueryEnhancement(et);
if (queryEnhancement.isPresent()) {
debugger.trace(this, "Query Enhancement found. Add WHERE condition of: %s", queryEnhancement.get().getClass()
.getName());
return queryEnhancement.get().getFilterExtension(cb, from);
}
return null;
}
protected JPANavigationPropertyInfo determineLastInfo(final List<JPANavigationPropertyInfo> navigationInfo) {
return navigationInfo.isEmpty() ? null : navigationInfo.get(navigationInfo.size() - 1);
}
protected final boolean determineTargetIsCollection(final UriInfoResource uriResource) {
final UriResource last = !uriResource.getUriResourceParts().isEmpty() ? uriResource.getUriResourceParts().get(
uriResource.getUriResourceParts().size() - 1) : null;
return (last instanceof final UriResourceProperty property && property.isCollection());
}
protected void expandPath(final JPAStructuredType st, final SelectionPathInfo<JPAPath> jpaPathList,
final String selectItem, final boolean targetIsCollection) throws ODataJPAModelException,
ODataJPAProcessException {
final JPAPath selectItemPath = st.getPath(selectItem);
if (selectItemPath == null)
throw new ODataJPAQueryException(QUERY_PREPARATION_INVALID_SELECTION_PATH, BAD_REQUEST);
if (selectItemPath.getLeaf().isComplex()) {
expandComplexPath(st, jpaPathList, targetIsCollection, selectItemPath);
} else if (selectItemPath.isTransient()) {
addTransientAttribute(st, jpaPathList, selectItemPath);
} else if (!selectItemPath.getLeaf().isCollection()
|| targetIsCollection) {// Primitive Type
jpaPathList.getODataSelections().add(selectItemPath);
}
}
private void expandComplexPath(final JPAStructuredType st, final SelectionPathInfo<JPAPath> jpaPathList,
final boolean targetIsCollection, final JPAPath selectItemPath) throws ODataJPAModelException,
ODataJPAProcessorException {
final List<JPAPath> child = st.searchChildPath(selectItemPath);
if (targetIsCollection) {
for (final JPAPath p : child) {
if (p.isTransient())
addTransientAttribute(st, jpaPathList, p);
else
jpaPathList.getODataSelections().add(p);
}
} else {
copySelectableProperties(jpaPathList, child);
}
}
private void addTransientAttribute(final JPAStructuredType st, final SelectionPathInfo<JPAPath> jpaPathList,
final JPAPath path) throws ODataJPAModelException, ODataJPAProcessorException {
buildRequiredSelections(st, path, jpaPathList.getRequiredSelections());
jpaPathList.getTransientSelections().add(path);
}
/*
* Create the join condition for a collection property. This attribute can be part of structure type, therefore the
* path to the collection property needs to be traversed
*/
protected void generateCollectionAttributeJoin(final Map<String, From<?, ?>> joinTables,
final Collection<JPAPath> jpaPathList, final JPANavigationPropertyInfoAccess lastInfo)
throws JPANoSelectionException,
ODataJPAProcessorException {
for (final JPAPath path : jpaPathList) {
// 1. check if path contains collection attribute
final JPAElement collection = findCollection(lastInfo, path);
// 2. Check if join exists and create join if not
addCollection(joinTables, path, collection);
}
}
@Override
protected Locale getLocale() {
return locale;
}
@Override
JPAODataRequestContextAccess getContext() {
return requestContext;
}
private void addCollection(final Map<String, From<?, ?>> joinTables, final JPAPath path,
final JPAElement collection) {
if (collection != null && !joinTables.containsKey(collection.getExternalName())) {
From<?, ?> from = target;
for (final JPAElement element : path.getPath()) {
from = from.join(element.getInternalName());
if (element instanceof JPACollectionAttribute) {
break;
}
}
joinTables.put(collection.getExternalName(), from);
}
}
private void addSkip(final TypedQuery<Tuple> typedQuery) {
if (lastInfo.getUriInfo().getSkipOption() != null)
typedQuery.setFirstResult(lastInfo.getUriInfo().getSkipOption().getValue());
}
private void addTop(final TypedQuery<Tuple> typedQuery) {
if (lastInfo.getUriInfo().getTopOption() != null)
typedQuery.setMaxResults(lastInfo.getUriInfo().getTopOption().getValue());
}
// Only for streams e.g. .../OrganizationImages('9')/$value
// Transient not possible
private List<JPAPath> buildPathValue(final JPAEntityType jpaEntity)
throws ODataApplicationException {
final List<JPAPath> jpaPathList = new ArrayList<>();
try {
// Stream value
jpaPathList.add(jpaEntity.getStreamAttributePath());
jpaPathList.addAll(jpaEntity.getKeyPath());
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
return jpaPathList;
}
private void buildRequiredSelections(final JPAStructuredType et, final JPAPath transientAttributePath,
final Set<JPAPath> requitedSelections) throws ODataJPAModelException, ODataJPAProcessorException {
final StringBuilder pathName = new StringBuilder();
JPAStructuredType st = et;
for (int i = 0; i < transientAttributePath.getPath().size() - 1; i++) {
final JPAElement element = transientAttributePath.getPath().get(i);
pathName.append(element.getExternalName()).append(JPAPath.PATH_SEPARATOR);
if (element instanceof final JPAAttribute attribute) {
st = attribute.getStructuredType();
}
}
for (final String internalName : transientAttributePath.getLeaf().getRequiredProperties()) {
final String externalName = st.getDeclaredAttribute(internalName)
.orElseThrow(() -> new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND,
HttpStatusCode.INTERNAL_SERVER_ERROR, internalName))
.getExternalName();
requitedSelections.add(et.getPath(pathName + externalName, false));
}
}
private void buildSelectionAddETag(final JPAEntityType jpaEntity, final Collection<JPAPath> jpaPathList)
throws ODataJPAModelException {
if (jpaEntity.hasEtag())
jpaPathList.add(jpaEntity.getEtagPath());
}
/**
* In order to be able to link the result of an expand query with the super-ordinate query it is necessary to ensure
* that the join columns are selected.<br>
* The same columns are required for the count query, for select as well as order by.
*
* @param uriResource
* @param jpaPathList
* @throws ODataApplicationException
* @throws ODataJPAQueryException
*/
private void buildSelectionAddExpandSelection(final UriInfoResource uriResource,
final Collection<JPAPath> jpaPathList)
throws ODataApplicationException {
final Map<JPAExpandItem, JPAAssociationPath> associationPathList = Utility.determineAssociations(sd, uriResource
.getUriResourceParts(), uriResource.getExpandOption());
if (!associationPathList.isEmpty()) {
final List<JPAPath> tmpPathList = new ArrayList<>(jpaPathList);
final List<JPAPath> addPathList = new ArrayList<>();
Collections.sort(tmpPathList);
for (final Entry<JPAExpandItem, JPAAssociationPath> item : associationPathList.entrySet()) {
final JPAAssociationPath associationPath = item.getValue();
try {
for (final JPAPath joinItem : associationPath.getLeftColumnsList()) {
final int pathIndex = Collections.binarySearch(tmpPathList, joinItem);
final int insertIndex = Collections.binarySearch(addPathList, joinItem);
if (pathIndex < 0 && insertIndex < 0)
addPathList.add(Math.abs(insertIndex) - 1, joinItem);
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
jpaPathList.addAll(addPathList);
}
}
private void buildSelectionAddKeys(final JPAEntityType jpaEntity, final Set<JPAPath> jpaPathList)
throws ODataJPAModelException {
for (final JPAAttribute key : jpaEntity.getKey()) {
jpaPathList.add(jpaEntity.getPath(key.getExternalName()));
}
}
private void buildSelectionAddMimeType(final JPAEntityType jpaEntity, final Collection<JPAPath> jpaPathList)
throws ODataJPAModelException {
if (jpaEntity.hasStream()) {
final JPAPath mimeTypeAttribute = jpaEntity.getContentTypeAttributePath();
if (mimeTypeAttribute != null) {
jpaPathList.add(mimeTypeAttribute);
}
}
}
private boolean checkCollectionIsPartOfGroup(final String collectionPath) throws ODataJPAProcessorException {
try {
final JPAPath path = jpaEntity.getPath(collectionPath);
if (path != null)
return path.isPartOfGroups(groups);
else
throw new ODataJPAProcessorException(MessageKeys.QUERY_PREPARATION_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR);
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private void convertSelectIntoPath(final SelectOption select, final SelectionPathInfo<JPAPath> jpaPathList,
final boolean targetIsCollection, final String pathPrefix) throws ODataJPAModelException,
ODataJPAProcessException {
for (final SelectItem sItem : select.getSelectItems()) {
final String pathItem = sItem.getResourcePath().getUriResourceParts()
.stream()
.map(path -> (path.getSegmentValue()))
.collect(Collectors.joining(JPAPath.PATH_SEPARATOR));
expandPath(jpaEntity, jpaPathList, pathPrefix.isEmpty() ? pathItem : pathPrefix + "/" + pathItem,
targetIsCollection);
}
}
/**
* Skips all those properties that are or belong to a collection property or marked as transient. E.g
* (Organization)Comment or (Person)InhouseAddress/Room
*
* @param selectablePathList
* @param allPathList
* @throws ODataJPAProcessorException
* @throws ODataJPAModelException
*/
private void copySelectableProperties(final SelectionPathInfo<JPAPath> selectablePathList,
final List<JPAPath> allPathList) throws ODataJPAProcessorException, ODataJPAModelException {
for (final JPAPath p : allPathList) {
if (isPropertySelectable(selectablePathList, p))
selectablePathList.getODataSelections().add(p);
}
}
private boolean isPropertySelectable(final SelectionPathInfo<JPAPath> selectablePathList, final JPAPath p)
throws ODataJPAModelException, ODataJPAProcessorException {
boolean selectable = true;
for (final JPAElement pathElement : p.getPath()) {
if (pathElement instanceof final JPAAttribute attribute) {
if (attribute.isTransient()) {
addTransientAttribute(jpaEntity, selectablePathList, p);
}
if (attribute.isCollection() || attribute.isTransient()) {
selectable = false;
break;
}
}
}
return selectable;
}
@SuppressWarnings("unchecked")
private <Y extends Comparable<? super Y>> jakarta.persistence.criteria.Expression<Boolean> createBoundaryEquals(
final JPAEntityType et, final From<?, ?> from, final JPAKeyPair jpaKeyPair) throws ODataJPAModelException,
ODataJPAQueryException {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
final List<JPAAttribute> keyElements = new ArrayList<>(et.getKey());
Collections.reverse(keyElements);
for (final JPAAttribute keyElement : keyElements) {
final var jpaPath = et.getPath(keyElement.getExternalName());
if (jpaPath != null) {
final Path<Y> keyPath = (Path<Y>) ExpressionUtility.<Comparable<?>> convertToCriteriaPath(from, jpaPath
.getPath());
final jakarta.persistence.criteria.Expression<Boolean> equalFragment = cb.equal(keyPath, jpaKeyPair.getMin()
.get(keyElement));
if (whereCondition == null)
whereCondition = equalFragment;
else
whereCondition = cb.and(whereCondition, equalFragment);
} else {
throw new ODataJPAQueryException(QUERY_RESULT_KEY_PROPERTY_ERROR, INTERNAL_SERVER_ERROR, et.getExternalName());
}
}
return whereCondition;
}
private <Y extends Comparable<? super Y>> jakarta.persistence.criteria.Expression<Boolean> createBoundaryWithUpper( // NOSONAR
final JPAEntityType et, final From<?, ?> from, final JPAKeyPair jpaKeyPair) throws ODataJPAModelException,
ODataJPAQueryException {
jakarta.persistence.criteria.Expression<Boolean> boundaryExpression = null;
final List<JPAAttribute> keyElements = new ArrayList<>(et.getKey());
// For all key attributes expect the last one
for (int primaryIndex = 0; primaryIndex < keyElements.size() - 1; primaryIndex++) {
jakarta.persistence.criteria.Expression<Boolean> expression = null;
for (int secondaryIndex = 0; secondaryIndex < primaryIndex; secondaryIndex++) {
final BoundaryInfo<Y> info = getBoundaryInfo(et, from, jpaKeyPair, keyElements, secondaryIndex);
expression = addWhereClause(expression, cb.equal(info.keyPath, info.lowerBoundary));
expression = addWhereClause(expression, cb.equal(info.keyPath, info.upperBoundary));
}
final BoundaryInfo<Y> info = getBoundaryInfo(et, from, jpaKeyPair, keyElements, primaryIndex);
expression = addWhereClause(expression, cb.greaterThan(info.keyPath, info.lowerBoundary));
expression = addWhereClause(expression, cb.lessThan(info.keyPath, info.upperBoundary));
boundaryExpression = orWhereClause(boundaryExpression, expression);
}
// Handle last key attribute
jakarta.persistence.criteria.Expression<Boolean> lowerExpression = null;
jakarta.persistence.criteria.Expression<Boolean> upperExpression = null;
for (int secondaryIndex = 0; secondaryIndex < keyElements.size() - 1; secondaryIndex++) {
final BoundaryInfo<Y> info = getBoundaryInfo(et, from, jpaKeyPair, keyElements, secondaryIndex);
lowerExpression = addWhereClause(lowerExpression, cb.equal(info.keyPath, info.lowerBoundary));
upperExpression = addWhereClause(upperExpression, cb.equal(info.keyPath, info.upperBoundary));
}
final BoundaryInfo<Y> info = getBoundaryInfo(et, from, jpaKeyPair, keyElements, keyElements.size() - 1);
lowerExpression = addWhereClause(lowerExpression, cb.greaterThanOrEqualTo(info.keyPath, info.lowerBoundary));
upperExpression = addWhereClause(upperExpression, cb.lessThanOrEqualTo(info.keyPath, info.upperBoundary));
if (keyElements.size() == 1) {
boundaryExpression = addWhereClause(boundaryExpression, lowerExpression);
boundaryExpression = addWhereClause(boundaryExpression, upperExpression);
} else {
boundaryExpression = orWhereClause(boundaryExpression, lowerExpression);
boundaryExpression = orWhereClause(boundaryExpression, upperExpression);
}
return boundaryExpression;
}
private <Y extends Comparable<? super Y>> BoundaryInfo<Y> getBoundaryInfo(final JPAEntityType et,
final From<?, ?> from, final JPAKeyPair jpaKeyPair, final List<JPAAttribute> keyElements,
final int secondaryIndex)
throws ODataJPAModelException, ODataJPAQueryException {
final JPAAttribute keyElement = keyElements.get(secondaryIndex);
return new BoundaryInfo<Y>(getKeyPath(et, from, keyElement), // NOSONAR
jpaKeyPair.getMinElement(keyElement),
jpaKeyPair.getMaxElement(keyElement));
}
@SuppressWarnings("unchecked")
private <Y extends Comparable<? super Y>> Path<Y> getKeyPath(final JPAEntityType et, final From<?, ?> from,
final JPAAttribute keyElement) throws ODataJPAModelException, ODataJPAQueryException {
final var jpaPath = et.getPath(keyElement.getExternalName());
if (jpaPath != null) {
return (Path<Y>) ExpressionUtility.<Comparable<?>> convertToCriteriaPath(from,
jpaPath.getPath());
} else {
throw new ODataJPAQueryException(QUERY_RESULT_KEY_PROPERTY_ERROR, INTERNAL_SERVER_ERROR, et
.getExternalName());
}
}
private void createFromClauseCollectionsJoins(final Map<String, From<?, ?>> joinTables)
throws ODataJPAQueryException, ODataJPAProcessorException {
try {
if (lastInfo.getAssociationPath() != null
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | true |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilderWatchDog.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilderWatchDog.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_CHECK_ASCENDING_REQUIRED_FOR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_CHECK_DESCENDING_REQUIRED_FOR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_CHECK_SORTING_NOT_SUPPORTED;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_CHECK_SORTING_NOT_SUPPORTED_FOR;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Order;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.helper.AbstractWatchDog;
/**
* In case an annotatable artifact has been annotated with Capabilities#SortRestrictions, it is checked that the
* generated ORDER BY fulfills the specified restrictions. See:
* <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.md#SortRestrictionsType"><i>SortRestrictions</i></a>
* @author Oliver Grande
* @since 1.1.1
* 20.03.2023
*/
public class JPAOrderByBuilderWatchDog extends AbstractWatchDog {
static final String DESCENDING_ONLY_PROPERTIES = "DescendingOnlyProperties";
static final String NON_SORTABLE_PROPERTIES = "NonSortableProperties";
static final String SORTABLE = "Sortable";
static final String ASCENDING_ONLY_PROPERTIES = "AscendingOnlyProperties";
static final String VOCABULARY_ALIAS = "Capabilities";
static final String TERM = "SortRestrictions";
private final Optional<CsdlAnnotation> annotation;
private final Map<String, CsdlExpression> properties;
private final String externalName;
JPAOrderByBuilderWatchDog(@Nonnull final JPAAnnotatable annotatable) throws ODataJPAQueryException {
try {
externalName = annotatable.getExternalName();
annotation = Optional.ofNullable(annotatable.getAnnotation(VOCABULARY_ALIAS, TERM));
properties = determineProperties();
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private Map<String, CsdlExpression> determineProperties() {
if (annotation.isPresent()) {
return getAnnotationProperties(annotation);
} else
return Collections.emptyMap();
}
JPAOrderByBuilderWatchDog() {
annotation = Optional.empty();
properties = Collections.emptyMap();
externalName = "";
}
void watch(final List<Order> result) throws ODataJPAQueryException {
if (annotation.isPresent()) {
watchSortable(result);
final List<CsdlExpression> nonSortable = getItems(properties, NON_SORTABLE_PROPERTIES);
final List<CsdlExpression> ascendingOnly = getItems(properties, ASCENDING_ONLY_PROPERTIES);
final List<CsdlExpression> descendingOnly = getItems(properties, DESCENDING_ONLY_PROPERTIES);
for (final Order orderBy : result) {
final String path = orderBy.getExpression().getAlias();
watchNonSortable(nonSortable, path);
watchAscendingOnly(ascendingOnly, orderBy, path);
watchDescendingOnly(descendingOnly, orderBy, path);
}
}
}
private void watchDescendingOnly(final List<CsdlExpression> descendingOnly, final Order orderBy, final String path)
throws ODataJPAQueryException {
for (final CsdlExpression descending : descendingOnly) {
if (descending.asDynamic().asPropertyPath().getValue().equals(path)
&& orderBy.isAscending())
throw new ODataJPAQueryException(QUERY_CHECK_DESCENDING_REQUIRED_FOR, HttpStatusCode.BAD_REQUEST,
externalName, path);
}
}
private void watchAscendingOnly(final List<CsdlExpression> ascendingOnly, final Order orderBy, final String path)
throws ODataJPAQueryException {
for (final CsdlExpression ascending : ascendingOnly) {
if (ascending.asDynamic().asPropertyPath().getValue().equals(path)
&& !orderBy.isAscending())
throw new ODataJPAQueryException(QUERY_CHECK_ASCENDING_REQUIRED_FOR, HttpStatusCode.BAD_REQUEST,
externalName, path);
}
}
private void watchNonSortable(final List<CsdlExpression> nonSortables, final String path)
throws ODataJPAQueryException {
for (final CsdlExpression nonSortable : nonSortables) {
if (nonSortable.asDynamic().asPropertyPath().getValue().equals(path))
throw new ODataJPAQueryException(QUERY_CHECK_SORTING_NOT_SUPPORTED_FOR, HttpStatusCode.BAD_REQUEST,
externalName, path);
}
}
private void watchSortable(final List<Order> result) throws ODataJPAQueryException {
if (!isSortable() && !result.isEmpty())
throw new ODataJPAQueryException(QUERY_CHECK_SORTING_NOT_SUPPORTED, HttpStatusCode.BAD_REQUEST,
externalName);
}
private boolean isSortable() {
return Optional.ofNullable(properties.get(SORTABLE))
.map(CsdlExpression::asConstant)
.map(CsdlConstantExpression::getValue)
.map(Boolean::valueOf)
.orElse(true);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemWrapper.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemWrapper.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.queryoption.ApplyOption;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption;
import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.FormatOption;
import org.apache.olingo.server.api.uri.queryoption.IdOption;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.uri.JPASkipOptionImpl;
import com.sap.olingo.jpa.processor.core.uri.JPATopOptionImpl;
// TODO In case of second level $expand expandItem.getResourcePath() returns an empty UriInfoResource => Bug or
// Feature?
public class JPAExpandItemWrapper implements JPAExpandItem, JPAExpandItemPageable {
private final ExpandItem item;
private final JPAEntityType jpaEntityType;
private Optional<JPAODataExpandPage> page;
private final List<UriResource> uriResourceParts;
public JPAExpandItemWrapper(final JPAServiceDocument sd, final ExpandItem item) throws ODataApplicationException {
super();
this.item = item;
this.uriResourceParts = item.getResourcePath() != null
? item.getResourcePath().getUriResourceParts()
: Collections.emptyList();
this.page = Optional.empty();
try {
this.jpaEntityType = sd.getEntity(Utility.determineTargetEntityType(getUriResourceParts()));
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ENTITY_UNKNOWN,
HttpStatusCode.BAD_REQUEST, e, Utility.determineTargetEntityType(getUriResourceParts()).getName());
}
}
public JPAExpandItemWrapper(final ExpandItem item, final JPAEntityType jpaEntityType) {
super();
this.item = item;
this.jpaEntityType = jpaEntityType;
this.uriResourceParts = item.getResourcePath() != null
? item.getResourcePath().getUriResourceParts()
: Collections.emptyList();
this.page = Optional.empty();
}
public JPAExpandItemWrapper(final ExpandItem item, final JPAEntityType jpaEntityType,
final UriResourcePartTyped uriResource) {
super();
this.item = item;
this.jpaEntityType = jpaEntityType;
this.uriResourceParts = Collections.singletonList(uriResource);
this.page = Optional.empty();
}
@Override
public List<CustomQueryOption> getCustomQueryOptions() {
return Collections.emptyList();
}
@Override
public ExpandOption getExpandOption() {
return item.getExpandOption();
}
@Override
public FilterOption getFilterOption() {
return item.getFilterOption();
}
@Override
public FormatOption getFormatOption() {
return null;
}
@Override
public IdOption getIdOption() {
return null;
}
@Override
public CountOption getCountOption() {
return item.getCountOption();
}
@Override
public OrderByOption getOrderByOption() {
return item.getOrderByOption();
}
@Override
public SearchOption getSearchOption() {
return item.getSearchOption();
}
@Override
public SelectOption getSelectOption() {
return item.getSelectOption();
}
@Override
public SkipOption getSkipOption() {
if (page.isPresent())
return new JPASkipOptionImpl(page.get().skip());
return item.getSkipOption();
}
@Override
public SkipTokenOption getSkipTokenOption() {
return null;
}
@Override
public TopOption getTopOption() {
if (page.isPresent())
return new JPATopOptionImpl(page.get().top());
return item.getTopOption();
}
@Override
public List<UriResource> getUriResourceParts() {
return uriResourceParts;
}
@Override
public String getValueForAlias(final String alias) {
return null;
}
/*
* (non-Javadoc)
*
* @see com.sap.olingo.jpa.processor.core.query.JPAExpandItem#getEntityType()
*/
@Override
public JPAEntityType getEntityType() {
return jpaEntityType;
}
@Override
public ApplyOption getApplyOption() {
return null;
}
@Override
public DeltaTokenOption getDeltaTokenOption() {
return null;
}
@Override
public Optional<JPAODataSkipTokenProvider> getSkipTokenProvider() {
if (page.isPresent())
return Optional.ofNullable(page.get().skipToken());
return Optional.empty();
}
@Override
public void setPage(final JPAODataExpandPage page) {
this.page = Optional.ofNullable(page);
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAKeyBoundary.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAKeyBoundary.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Objects;
import javax.annotation.Nonnull;
/**
*
*
* @author Oliver Grande
* Created: 10.11.2019
*
*/
public class JPAKeyBoundary {
private final int noHops;
private final JPAKeyPair keyBoundary;
JPAKeyBoundary(int noHops, @Nonnull JPAKeyPair keyBoundary) {
super();
this.noHops = noHops;
this.keyBoundary = Objects.requireNonNull(keyBoundary);
}
public int getNoHops() {
return noHops;
}
public JPAKeyPair getKeyBoundary() {
return keyBoundary;
}
@Override
public String toString() {
return "JPAKeyBoundary [noHops=" + noHops + ", keyBoundary=" + keyBoundary + "]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemPageable.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemPageable.java | package com.sap.olingo.jpa.processor.core.query;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
public interface JPAExpandItemPageable {
void setPage(JPAODataExpandPage page);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilder.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAOrderByBuilder.java | package com.sap.olingo.jpa.processor.core.query;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.properties.JPAOrderByPropertyFactory;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
/**
* Constructor of Order By clause.
* @author Oliver Grande
* @since 1.0.0
*/
final class JPAOrderByBuilder {
private static final String ORDER_BY_LO_ENTRY = "Determined relationship and add corresponding to OrderBy";
private static final Log LOGGER = LogFactory.getLog(JPAOrderByBuilder.class);
private static final String LOG_ORDER_BY = "Determined $orderby: convert to Order By";
private final JPAEntityType jpaEntity;
private final From<?, ?> target;
private final CriteriaBuilder cb;
private final List<String> groups;
private final JPAOrderByBuilderWatchDog watchDog;
JPAOrderByBuilder(final JPAEntityType jpaEntity, final From<?, ?> target, final CriteriaBuilder cb,
final List<String> groups) {
super();
this.jpaEntity = jpaEntity;
this.target = target;
this.cb = cb;
this.groups = groups;
this.watchDog = new JPAOrderByBuilderWatchDog();
}
JPAOrderByBuilder(final JPAAnnotatable annotatable, final JPAEntityType jpaEntity, final From<?, ?> target,
final CriteriaBuilder cb, final List<String> groups) throws ODataJPAQueryException {
super();
this.jpaEntity = jpaEntity;
this.target = target;
this.cb = cb;
this.groups = groups;
this.watchDog = new JPAOrderByBuilderWatchDog(annotatable);
}
/**
* Create a list of order by for the root (non $expand) query part. Beside the $orderby query option, it also take
* $top, $skip and an optional server driven paging into account, so that for the later once a stable sorting is
* guaranteed.
* <p>
* If asc or desc is not specified, the service MUST order by the specified property in ascending order.
* See: <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398305"
* >OData Version 4.0 Part 1 - 11.2.5.2 System Query Option $orderby</a>
* <p>
*
* Some OData example requests:<br>
* .../Organizations?$orderby=Address/Country --> one item, two resourcePaths
* [...ComplexProperty,...PrimitiveProperty]<br>
* .../Organizations?$orderby=Roles/$count --> one item, two resourcePaths [...NavigationProperty,...Count]<br>
* .../Organizations?$orderby=Roles/$count desc,Address/Country asc -->two items
* .../AdminustrativeDivision?$orderby=Parent/DivisionCode
* <p>
* SQL example to order by number of entities
* <p>
* <code>
* SELECT t0."BusinessPartnerID" ,COUNT(t1."BusinessPartnerID")
* <pre>FROM "OLINGO"."org.apache.olingo.jpa::BusinessPartner" t0 <br>
* LEFT OUTER JOIN "OLINGO"."org.apache.olingo.jpa::BusinessPartnerRole" t1 <br>
* ON (t1."BusinessPartnerID" = t0."BusinessPartnerID")}
* WHERE (t0."Type" = ?)<br>
* GROUP BY t0."BusinessPartnerID"<br>
* ORDER BY COUNT(t1."BusinessPartnerID") DESC<br></pre>
* </code>
* @since 1.0.0
* @param joinTables
* @param uriResource
* @param uriInfoResource
* @param orderByPaths: A collection of paths to the properties within the ORDER BY clause
* @return A list of generated orderby clauses
* @throws ODataApplicationException
*/
@Nonnull
List<Order> createOrderByList(@Nonnull final Map<String, From<?, ?>> joinTables,
final List<JPAProcessorAttribute> orderByAttributes, final UriInfoResource uriInfoResource)
throws ODataJPAQueryException {
final List<Order> result = new ArrayList<>();
try {
if (uriInfoResource != null
&& (uriInfoResource.getTopOption() != null
|| uriInfoResource.getSkipOption() != null)) {
LOGGER.trace("Determined $top/$skip or page: add primary key to Order By");
final var factory = new JPAOrderByPropertyFactory();
for (final var key : jpaEntity.getKey()) {
if (!containsAttribute(orderByAttributes, key))
orderByAttributes.add(factory.createProperty(target, jpaEntity.getPath(key.getExternalName()), cb));
}
}
if (!orderByAttributes.isEmpty()) {
LOGGER.trace(LOG_ORDER_BY);
addOrderByProperties(orderByAttributes, result);
watchDog.watch(result);
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, BAD_REQUEST);
}
return result;
}
private boolean containsAttribute(final List<JPAProcessorAttribute> orderByAttributes, final JPAAttribute key)
throws ODataJPAModelException {
var found = false;
for (final var attribute : orderByAttributes) {
found = attribute.getJPAPath().equals(jpaEntity.getPath(key.getExternalName()));
if (found)
break;
}
return found;
}
@Nonnull
List<Order> createOrderByList(final Map<String, From<?, ?>> joinTables) {
return Collections.emptyList();
}
/**
* For row number query with join table
* @param association
* @return
* @throws ODataApplicationException
*/
List<Order> createOrderByList(final JPAAssociationPath association)
throws ODataApplicationException {
final List<Order> result = new ArrayList<>();
addOrderByInvertJoinCondition(association, result);
return result;
}
/**
* Create a list of order by for $expand query part. It does not take top and skip into account, but the
* association.
* <p>
* @throws ODataApplicationException
*/
@Nonnull
List<Order> createOrderByList(final Map<String, From<?, ?>> joinTables,
final List<JPAProcessorAttribute> orderByAttributes, @Nonnull final JPAAssociationPath association)
throws ODataApplicationException {
final List<Order> result = new ArrayList<>();
addOrderByJoinCondition(orderByAttributes, association);
addOrderByProperties(orderByAttributes, result);
return result;
}
@Nonnull
List<Order> createOrderByListAlias(@Nonnull final Map<String, From<?, ?>> joinTables,
final List<JPAProcessorAttribute> orderByAttributes, @Nonnull final JPAAssociationPath association)
throws ODataApplicationException {
final List<Order> result = new ArrayList<>();
addOrderByJoinConditionAlias(association, result);
addOrderByProperties(orderByAttributes, result);
return result;
}
@Nonnull
List<Order> createOrderByList(@Nonnull final Map<String, From<?, ?>> joinTables,
final List<JPAProcessorAttribute> orderByAttributes) throws ODataApplicationException {
final List<Order> result = new ArrayList<>();
addOrderByProperties(orderByAttributes, result);
return result;
}
void addOrderByProperties(final List<JPAProcessorAttribute> orderByAttributes, final List<Order> result)
throws ODataJPAQueryException {
for (final var attribute : orderByAttributes) {
result.add(attribute.createOrderBy(cb, groups));
}
}
void addOrderByJoinConditionAlias(final JPAAssociationPath association, final List<Order> orders)
throws ODataApplicationException {
LOGGER.trace(ORDER_BY_LO_ENTRY);
try {
final List<JPAPath> joinColumns = association.hasJoinTable()
? asPathList(association) : association.getRightColumnsList();
for (final JPAPath j : joinColumns) {
final Path<Object> jpaProperty = target.get(j.getAlias());
orders.add(cb.asc(jpaProperty));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
void addOrderByJoinCondition(final List<JPAProcessorAttribute> orderByAttributes,
final JPAAssociationPath association) throws ODataApplicationException {
LOGGER.trace(ORDER_BY_LO_ENTRY);
try {
final var factory = new JPAOrderByPropertyFactory();
final List<JPAPath> joinColumns = association.hasJoinTable()
? asPathList(association) : association.getRightColumnsList();
for (var i = joinColumns.size() - 1; i >= 0; i--) {
final JPAPath joinPath = joinColumns.get(i);
orderByAttributes.add(0, factory.createProperty(target, joinPath, cb));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
void addOrderByInvertJoinCondition(final JPAAssociationPath association, final List<Order> orders)
throws ODataApplicationException {
LOGGER.trace(ORDER_BY_LO_ENTRY);
try {
final List<JPAPath> joinColumns = association.hasJoinTable()
? asInvertPathList(association) : association.getLeftColumnsList();
for (final JPAPath j : joinColumns) {
Path<?> jpaProperty = target;
for (final JPAElement pathElement : j.getPath()) {
jpaProperty = jpaProperty.get(pathElement.getInternalName());
}
orders.add(cb.asc(jpaProperty));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
private List<JPAPath> asPathList(final JPAAssociationPath association) throws ODataJPAModelException {
final List<JPAOnConditionItem> joinColumns = association.getJoinTable().getJoinColumns();
return joinColumns.stream()
.map(JPAOnConditionItem::getRightPath)
.toList();
}
private List<JPAPath> asInvertPathList(final JPAAssociationPath association) throws ODataJPAModelException {
final List<JPAOnConditionItem> joinColumns = association.getJoinTable().getJoinColumns();
return joinColumns.stream()
.map(JPAOnConditionItem::getLeftPath)
.toList();
}
@SuppressWarnings("unchecked")
<X extends Object, Y extends Object> From<X, Y> determineParentFrom(final JPAAssociationPath association,
final List<JPANavigationPropertyInfo> navigationInfo) throws ODataJPAQueryException {
for (final JPANavigationPropertyInfo item : navigationInfo) {
if (item.getAssociationPath() == association) {
return (From<X, Y>) item.getFromClause();
}
}
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR,
HttpStatusCode.BAD_REQUEST);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/InExpressionValue.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/InExpressionValue.java | package com.sap.olingo.jpa.processor.core.query;
/**
* Tag interface to indicate that a sub query shall be used for an IN expression
* @author Oliver Grande
* @since 2.0.1
* 20.11.2023
*/
public interface InExpressionValue {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandSubQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaQuery;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
/**
* Requires Processor Query
*
* @author Oliver Grande
* @since 1.0.1
* 25.11.2020
*/
public class JPAExpandSubQuery extends JPAAbstractExpandSubQuery implements JPAExpandQuery {
public JPAExpandSubQuery(final OData odata, final JPAInlineItemInfo item,
final JPAODataRequestContextAccess requestContext) throws ODataException {
super(odata, requestContext, item);
}
@Override
public JPAExpandQueryResult execute() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "execute")) {
final JPAQueryCreationResult tupleQuery = createTupleQuery();
final List<Tuple> intermediateResult = tupleQuery.query().getResultList();
final Map<String, List<Tuple>> result = convertResult(intermediateResult);
return new JPAExpandQueryResult(result, count(), jpaEntity, tupleQuery.selection().joinedRequested(),
skipTokenProvider);
} catch (final JPANoSelectionException e) {
return new JPAExpandQueryResult(emptyMap(), emptyMap(), this.jpaEntity, emptyList(), Optional.empty());
} catch (final ODataApplicationException e) {
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(), INTERNAL_SERVER_ERROR.getStatusCode(), getLocale(),
e);
}
}
private List<Selection<?>> createSelectClause(final Map<String, From<?, ?>> joinTables, // NOSONAR
final Collection<JPAPath> requestedProperties, final List<String> groups)
throws ODataApplicationException {
List<Selection<?>> selections = List.of();
try {
if (hasRowLimit(lastInfo)) {
selections = new ArrayList<>(requestedProperties.size());
for (final JPAPath jpaPath : requestedProperties) {
if (jpaPath.isPartOfGroups(groups)) {
final Path<?> path = target.get(jpaPath.getAlias());
path.alias(jpaPath.getAlias());
selections.add(path);
}
}
} else {
selections = super.createSelectClause(joinTables, requestedProperties, target, groups);
}
selections = addSelectJoinTable(selections);
return selections;
} finally {
debugger.trace(this, "Determined selections %s", selections.toString());
}
}
@Override
final Map<String, Long> count() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "count")) {
if (countRequested(lastInfo)) {
final JPAExpandSubCountQuery countQuery = new JPAExpandSubCountQuery(odata, requestContext, jpaEntity,
association, navigationInfo);
return countQuery.count();
}
return emptyMap();
} catch (final ODataException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
private Map<String, List<Tuple>> convertResult(final List<Tuple> intermediateResult)
throws ODataApplicationException {
String joinKey = "";
List<Tuple> subResult = null;
final Map<String, List<Tuple>> convertedResult = new HashMap<>();
for (final Tuple row : intermediateResult) {
String actualKey;
try {
actualKey = buildConcatenatedKey(row, association);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, BAD_REQUEST);
}
if (!actualKey.equals(joinKey)) {
subResult = new ArrayList<>();
convertedResult.put(actualKey, subResult);
joinKey = actualKey;
}
if (subResult != null) {
subResult.add(row);
}
}
return convertedResult;
}
private List<Order> createOrderBy(final Map<String, From<?, ?>> joinTables,
final List<JPAProcessorAttribute> orderByAttributes) throws ODataApplicationException {
final JPAOrderByBuilder orderByBuilder = new JPAOrderByBuilder(jpaEntity, root, cb, groups);
if (association.hasJoinTable() && hasRowLimit(lastInfo)) {
return orderByBuilder.createOrderByList(association);
} else if (hasRowLimit(lastInfo)) {
return orderByBuilder.createOrderByListAlias(joinTables, orderByAttributes, association);
} else {
return orderByBuilder.createOrderByList(joinTables, orderByAttributes, association);
}
}
/**
* Create top level expand query including an inner query with a row number window function in case this is necessary
* @param selectionPath
* @return
* @throws ODataException
*/
private JPAQueryPair createQueries(final SelectionPathInfo<JPAPath> selectionPath) throws ODataException {
if (hasRowLimit(lastInfo)) {
debugger.trace(this, "Row number required");
final int lastIndex = navigationInfo.size() - 2;
final JPAAssociationPath childAssociation = navigationInfo.get(lastIndex).getAssociationPath();
final JPARowNumberFilterQuery rowNumberQuery = new JPARowNumberFilterQuery(odata, requestContext, lastInfo,
this, association, childAssociation, selectionPath);
return new JPAQueryPair(rowNumberQuery, this);
} else {
debugger.trace(this, "Row number not required");
return new JPAQueryPair(this, this);
}
}
private @Nonnull JPAQueryCreationResult createTupleQuery() throws JPANoSelectionException,
ODataException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createTupleQuery")) {
final ProcessorCriteriaQuery<Tuple> tupleQuery = (ProcessorCriteriaQuery<Tuple>) cq;
final var orderByAttributes = getOrderByAttributes(uriResource.getOrderByOption());
final SelectionPathInfo<JPAPath> selectionPath = buildSelectionPathList(this.uriResource);
final JPAQueryPair queries = createQueries(selectionPath);
addFilterCompiler(lastInfo);
final LinkedList<JPAAbstractQuery> hops = buildSubQueries(queries.inner());
final Subquery<Object> subQuery = linkSubQueries(hops);
final Map<String, From<?, ?>> joinTables = createJoinTables(tupleQuery, selectionPath, orderByAttributes,
subQuery);
tupleQuery.where(createWhere(subQuery, lastInfo));
tupleQuery.multiselect(createSelectClause(joinTables, selectionPath.joinedPersistent(), groups));
tupleQuery.orderBy(createOrderBy(joinTables, orderByAttributes));
tupleQuery.distinct(orderByAttributes.isEmpty());
if (!orderByAttributes.isEmpty()) {
cq.groupBy(createGroupBy(joinTables, target, selectionPath.joinedPersistent(), orderByAttributes));
}
final TypedQuery<Tuple> query = em.createQuery(tupleQuery);
return new JPAQueryCreationResult(query, selectionPath);
}
}
Map<String, From<?, ?>> createJoinTables(final ProcessorCriteriaQuery<Tuple> tupleQuery,
final SelectionPathInfo<JPAPath> selectionPath, final List<JPAProcessorAttribute> orderByAttributes,
final Subquery<Object> subQuery) throws ODataApplicationException, JPANoSelectionException {
Map<String, From<?, ?>> joinTables = new HashMap<>();
if (hasRowLimit(lastInfo)) {
this.target = this.root = tupleQuery.from((ProcessorSubquery<?>) subQuery);
} else {
joinTables = createFromClause(emptyList(), selectionPath.joinedPersistent(), cq, lastInfo);
}
createFromClauseOrderBy(orderByAttributes, joinTables, root);
return joinTables;
}
@Override
Expression<Boolean> createWhere(final Subquery<?> subQuery, final JPANavigationPropertyInfo navigationInfo)
throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createWhere")) {
if (hasRowLimit(lastInfo)) {
return createWhereByRowNumber(target, lastInfo);
}
return super.createWhere(subQuery, navigationInfo);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQueryFactory.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Optional;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
public class JPAExpandQueryFactory {
private final OData odata;
private final JPAODataRequestContextAccess requestContext;
private final CriteriaBuilder cb;
public JPAExpandQueryFactory(final OData odata, final JPAODataRequestContextAccess requestContext,
final CriteriaBuilder cb) {
this.odata = odata;
this.requestContext = requestContext;
this.cb = cb;
}
public JPAExpandQuery createQuery(final JPAExpandItemInfo item, final Optional<JPAKeyBoundary> keyBoundary)
throws ODataException {
if (cb instanceof ProcessorCriteriaBuilder)
return new JPAExpandSubQuery(odata, item, requestContext);
return new JPAExpandJoinQuery(odata, item, requestContext, keyBoundary);
}
public JPAExpandCountQuery createCountQuery(final JPAExpandItemInfo item,
final Optional<JPAKeyBoundary> keyBoundary) throws ODataException {
if (cb instanceof ProcessorCriteriaBuilder)
return new JPAExpandSubCountQuery(odata, item, requestContext);
return new JPAExpandJoinCountQuery(odata, requestContext, item, keyBoundary);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAJoinQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAJoinQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
public class JPAJoinQuery extends JPAAbstractRootJoinQuery implements JPAQuery {
public JPAJoinQuery(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
}
@Override
public JPAConvertibleResult execute() throws ODataApplicationException {
// Pre-process URI parameter, so they can be used at different places
final var selectionPath = buildSelectionPathList(this.uriResource);
try (var measurement = debugger.newMeasurement(this, "execute")) {
final var orderByAttributes = getOrderByAttributes(uriResource.getOrderByOption());
final var joinTables = createFromClause(orderByAttributes, selectionPath.joinedPersistent(), cq,
lastInfo);
cq.multiselect(createSelectClause(joinTables, selectionPath.joinedPersistent(), target, groups))
.distinct(determineDistinct());
final var whereClause = createWhere();
if (whereClause != null) {
cq.where(whereClause);
}
cq.orderBy(createOrderByBuilder().createOrderByList(joinTables, orderByAttributes, lastInfo.getUriInfo()));
if (orderByAttributes.stream().anyMatch(JPAProcessorAttribute::requiresJoin)) {
cq.groupBy(createGroupBy(joinTables, root, selectionPath.joinedPersistent(), orderByAttributes));
}
final TypedQuery<Tuple> typedQuery = em.createQuery(cq);
addTopSkip(typedQuery);
final var result = new HashMap<String, List<Tuple>>(1);
List<Tuple> intermediateResult;
try (var resultMeasurement = debugger.newMeasurement(this, "getResultList")) {
intermediateResult = typedQuery.getResultList();
}
result.put(ROOT_RESULT_KEY, intermediateResult);
return returnResult(selectionPath.joinedRequested(), result);
} catch (final JPANoSelectionException e) {
return returnEmptyResult(selectionPath.joinedRequested());
}
}
private JPAOrderByBuilder createOrderByBuilder() throws ODataJPAQueryException {
if (entitySet.isPresent()) {
return new JPAOrderByBuilder(entitySet.get(), jpaEntity, target, cb, groups);
}
return new JPAOrderByBuilder(jpaEntity, target, cb, groups);
}
public List<JPANavigationPropertyInfo> getNavigationInfo() {
return navigationInfo;
}
/**
* Desired if SELECT DISTINCT shall be generated. This is required e.g. if multiple values for the same claims are
* present. As a DISTINCT is usually slower the decision algorithm my need to be enhanced in the future
* @return
*/
private boolean determineDistinct() {
return claimsProvider.isPresent();
}
private JPAConvertibleResult returnEmptyResult(final Collection<JPAPath> selectionPath) {
if (lastInfo.getAssociationPath() != null
&& (lastInfo.getAssociationPath().getLeaf() instanceof JPACollectionAttribute)) {
return new JPACollectionQueryResult(jpaEntity, lastInfo.getAssociationPath(), selectionPath);
}
return new JPAExpandQueryResult(jpaEntity, selectionPath);
}
private JPAConvertibleResult returnResult(@Nonnull final Collection<JPAPath> selectionPath,
final HashMap<String, List<Tuple>> result) throws ODataApplicationException {
final var odataEntityType = determineODataTargetEntityType(requestContext);
if (lastInfo.getAssociationPath() != null
&& (lastInfo.getAssociationPath().getLeaf() instanceof JPACollectionAttribute)) {
return new JPACollectionQueryResult(result, null, odataEntityType, lastInfo.getAssociationPath(), selectionPath);
}
return new JPAExpandQueryResult(result, Collections.emptyMap(), odataEntityType, selectionPath, Optional.empty());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandItemInfo.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
public final class JPAExpandItemInfo extends JPAInlineItemInfo {
private static final Log LOGGER = LogFactory.getLog(JPAExpandItemInfo.class);
JPAExpandItemInfo(final JPAServiceDocument sd, final JPAExpandItem uriInfo,
final JPAAssociationPath expandAssociation, final List<JPANavigationPropertyInfo> hops)
throws ODataApplicationException {
super(uriInfo, expandAssociation, hops);
for (final JPANavigationPropertyInfo predecessor : hops)
this.hops.add(new JPANavigationPropertyInfo(predecessor));
this.hops.get(this.hops.size() - 1).setAssociationPath(expandAssociation);
if (!uriInfo.getUriResourceParts().isEmpty())
this.hops.addAll(Utility.determineNavigationPath(sd, uriInfo.getUriResourceParts(), uriInfo));
else
this.hops.add(new JPANavigationPropertyInfo(sd, null, uriInfo, uriInfo.getEntityType()));
}
public JPAExpandItemInfo(final JPAExpandItemInfo expandItem, final Optional<JPAODataExpandPage> page) {
super(setPage(expandItem.uriInfo, expandItem.expandAssociation, page), expandItem.expandAssociation,
expandItem.parentHops);
this.hops.addAll(expandItem.hops);
}
private static JPAExpandItem setPage(final JPAExpandItem uriInfo, final JPAAssociationPath expandAssociation,
final Optional<JPAODataExpandPage> page) {
if (page.isPresent() && uriInfo instanceof final JPAExpandItemPageable pageable) {
LOGGER.trace("Server driven paging found on " + expandAssociation.getAlias());
pageable.setPage(page.get());
}
return uriInfo;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAJoinCountQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAJoinCountQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collections;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
public class JPAJoinCountQuery extends JPAAbstractRootJoinQuery implements JPACountQuery {
public JPAJoinCountQuery(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
}
/**
* Fulfill $count requests. For details see
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752288"
* >OData Version 4.0 Part 1 - 11.2.5.5 System Query Option $count</a>
* @return
* @throws ODataApplicationException
*/
@Override
public Long countResults() throws ODataApplicationException {
/*
* URL example:
* .../Organizations?$count=true
* .../Organizations/$count
* .../Organizations('3')/Roles/$count
*/
try (var measurement = debugger.newMeasurement(this, "countResults")) {
new JPACountWatchDog(entitySet.map(JPAAnnotatable.class::cast)).watch(this.uriResource);
createFromClause(Collections.emptyList(), Collections.emptyList(), cq, lastInfo);
final var whereClause = createWhere();
if (whereClause != null)
cq.where(whereClause);
cq.multiselect(cb.count(target));
final var result = em.createQuery(cq).getSingleResult();
return ((Number) result.get(0)).longValue();
} catch (final JPANoSelectionException e) {
return 0L;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationPropertyInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationPropertyInfo.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.criteria.From;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourceSingleton;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterComplier;
public final class JPANavigationPropertyInfo implements JPANavigationPropertyInfoAccess {
private static final Log LOGGER = LogFactory.getLog(JPANavigationPropertyInfo.class);
private final JPAServiceDocument sd;
private final UriResourcePartTyped navigationTarget;
private JPAAssociationPath associationPath;
private final List<UriParameter> keyPredicates;
private From<?, ?> fromClause = null;
private final UriInfoResource uriInfo;
private JPAEntityType et = null;
private JPAFilterComplier filterCompiler = null;
/**
*
* Copy constructor, that does not copy the <i>from</i> clause, so the new JPANavigationPropertyInfo can be used in a
* new query.
* @param original
*/
public JPANavigationPropertyInfo(final JPANavigationPropertyInfo original) {
this.navigationTarget = original.getUriResource();
this.associationPath = original.getAssociationPath();
this.keyPredicates = original.getKeyPredicates();
this.uriInfo = original.getUriInfo();
this.sd = original.getServiceDocument();
this.et = this.uriInfo instanceof JPAExpandItem ? ((JPAExpandItem) uriInfo).getEntityType() : null;
}
public JPANavigationPropertyInfo(final JPAServiceDocument sd, final JPAAssociationPath associationPath,
final UriInfoResource uriInfo, final JPAEntityType et) {
super();
this.navigationTarget = null;
this.associationPath = associationPath;
this.keyPredicates = Collections.emptyList();
this.uriInfo = uriInfo;
this.sd = sd;
this.et = et;
}
public JPANavigationPropertyInfo(final JPAServiceDocument sd, final UriResourcePartTyped uriResource,
final JPAAssociationPath associationPath, final UriInfoResource uriInfo) throws ODataApplicationException {
this.navigationTarget = uriResource;
this.associationPath = associationPath;
this.keyPredicates = uriResource.isCollection() ? Collections.emptyList() : Utility.determineKeyPredicates(
uriResource);
this.uriInfo = uriInfo;
this.sd = sd;
}
@Override
public JPAAssociationPath getAssociationPath() {
return associationPath;
}
@Override
public UriResourcePartTyped getUriResource() {
return navigationTarget;
}
/**
* Set the association path to a other entity.
* @param associationPath
*/
public void setAssociationPath(final JPAAssociationPath associationPath) {
assert this.associationPath == null;
this.associationPath = associationPath;
}
JPAEntityType getEntityType() throws ODataJPAModelException {
if (et != null)
return et;
return determineEntityType();
}
private JPAEntityType determineEntityType() throws ODataJPAModelException {
final UriResourcePartTyped resource = getUriResource();
String castFrom = null;
if (resource instanceof final UriResourceEntitySet entitySet) {
et = sd.getEntity(entitySet.getEntitySet().getName());
if (entitySet.getTypeFilterOnCollection() != null) {
et = sd.getEntity(entitySet.getTypeFilterOnCollection());
castFrom = ((UriResourceEntitySet) resource).getEntitySet().getName();
} else if (entitySet.getTypeFilterOnEntry() != null) {
et = sd.getEntity(entitySet.getTypeFilterOnEntry());
castFrom = entitySet.getEntitySet().getName();
}
} else if (resource instanceof final UriResourceSingleton singleton) {
et = sd.getEntity(singleton.getSingleton().getName());
if (singleton.getEntityTypeFilter() != null) {
et = sd.getEntity(singleton.getEntityTypeFilter());
castFrom = singleton.getSingleton().getName();
}
} else if (resource instanceof final UriResourceNavigation navigation) {
et = sd.getEntity(resource.getType());
if (navigation.getTypeFilterOnEntry() != null) {
et = sd.getEntity(navigation.getTypeFilterOnEntry());
castFrom = navigation.getProperty().getName();
} else if (navigation.getTypeFilterOnCollection() != null) {
et = sd.getEntity(navigation.getTypeFilterOnCollection());
castFrom = navigation.getProperty().getName();
}
} else {
et = sd.getEntity(resource.getType());
}
if (et == null)
throw new ODataJPAModelException(ODataJPAModelException.MessageKeys.JOIN_TABLE_NOT_FOUND);
if (castFrom != null)
LOGGER.trace("Found cast from " + castFrom + " to " + et.getExternalName());
return et;
}
JPAFilterComplier getFilterCompiler() {
return filterCompiler;
}
From<?, ?> getFromClause() { // NOSONAR
return fromClause;
}
@Override
public List<UriParameter> getKeyPredicates() {
return keyPredicates;
}
UriInfoResource getUriInfo() {
return uriInfo;
}
void setFilterCompiler(final JPAFilterComplier filterCompiler) {
assert this.filterCompiler == null;
this.filterCompiler = filterCompiler;
}
/**
* Set the from clause. This is possible only once and can not be changed later.
* @param from
*/
void setFromClause(final From<?, ?> from) {
assert fromClause == null;
fromClause = from;
}
private JPAServiceDocument getServiceDocument() {
return sd;
}
@Override
public String toString() {
try {
final String typeName = getEntityType().getExternalName();
final String associationName = associationPath != null ? associationPath.getAlias() : "";
return "JPANavigationPropertyInfo [et=" + typeName
+ ", associationPath=" + associationName + "]";
} catch (final ODataJPAModelException e) {
return super.toString();
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAQueryPair.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAQueryPair.java | package com.sap.olingo.jpa.processor.core.query;
record JPAQueryPair(JPAAbstractQuery inner, JPAAbstractQuery outer) {
@Override
public String toString() {
return "JPAQueryPair [outer=" + outer + ", inner=" + inner + "]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQueryBuilder.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationFilterQueryBuilder.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceLambdaVariable;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.queryoption.expression.Binary;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPANotImplementedException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPACountExpression;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterExpression;
import com.sap.olingo.jpa.processor.core.filter.JPAMemberOperator;
import com.sap.olingo.jpa.processor.core.filter.JPANullExpression;
import com.sap.olingo.jpa.processor.core.filter.JPAVisitableExpression;
/**
* Three types of navigation filter queries have to be supported:
* <ol>
* <li>Filter on a given value: AdministrativeDivisions?$filter=Parent/Parent/CodeID eq 'NUTS1' and DivisionCode eq
* 'BE212'</li>
* <li>Filter on the number of items of the relation target:
* CollectionDeeps?$filter=FirstLevel/SecondLevel/Comment/$count eq 2</li>
* <li>Filter on the existence (to one) of an item: AssociationOneToOneSources?$filter=ColumnTarget eq null</li>
* </ol>
* The builder creates the corresponding query implementation.
* @author Oliver Grande
* @since 1.1.1
* 28.07.2023
*/
public class JPANavigationFilterQueryBuilder {
private static final String NULL = "null";
private final CriteriaBuilder cb;
private OData odata;
private JPAServiceDocument sd;
private JPAAbstractQuery parent;
private EntityManager em;
private JPAAssociationPath association;
private VisitableExpression expression;
private From<?, ?> from;
private Optional<JPAODataClaimProvider> claimsProvider;
private List<String> groups;
private List<UriParameter> keyPredicates;
private UriResourcePartTyped uriResource;
public JPANavigationFilterQueryBuilder(final CriteriaBuilder cb) {
this.cb = cb;
}
public JPANavigationSubQuery build() throws ODataApplicationException {
final JPANavigationSubQuery query;
final JPAEntityType type = determineJpaEntityType();
if (expression != null && getAggregationType(expression) != null) {
if (asInQuery())
query = new JPANavigationCountForInQuery(odata, sd,
type, em, parent, from, association, claimsProvider, keyPredicates);
else
query = new JPANavigationCountForExistsQuery(odata, sd,
type, em, parent, from, association, claimsProvider, keyPredicates);
} else if (expression != null && isNullExpression(expression)) {
query = new JPANavigationNullQuery(odata, sd,
type, em, parent, from, association, claimsProvider, keyPredicates);
} else {
query = new JPANavigationFilterQuery(odata, sd,
type, em, parent, from, association, claimsProvider, keyPredicates);
}
query.buildExpression(expression, groups);
return query;
}
private JPAEntityType determineJpaEntityType() throws ODataJPAQueryException, ODataJPANotImplementedException {
if (uriResource instanceof UriResourceProperty) {
return determineEntityType(association);
} else {
// ((UriResourceLambdaVariable)((Member)((Binary)expression).getLeftOperand()).getResourcePath().getUriResourceParts().get(0)).getSegmentValue(true)
if (expression instanceof Binary binaryExpression
&& binaryExpression.getLeftOperand() instanceof Member memberExpression
&& memberExpression.getResourcePath() != null
&& memberExpression.getResourcePath().getUriResourceParts() != null
&& !memberExpression.getResourcePath().getUriResourceParts().isEmpty()
&& memberExpression.getResourcePath().getUriResourceParts().get(
0) instanceof UriResourceLambdaVariable lambda) {
var variableParts = lambda.getSegmentValue(true).split("/");
if (variableParts.length == 2) {
var cast = sd.getEntity(new FullQualifiedName(variableParts[1]));
if (cast != null)
return cast;
} else if (variableParts.length > 2) {
throw new ODataJPANotImplementedException("Chained cast not supported");
}
}
return asJPAEntityType((EdmEntityType) uriResource.getType());
}
}
public JPANavigationFilterQueryBuilder setOdata(final OData odata) {
this.odata = odata;
return this;
}
public JPANavigationFilterQueryBuilder setServiceDocument(final JPAServiceDocument sd) {
this.sd = sd;
return this;
}
public JPANavigationFilterQueryBuilder setNavigationInfo(final JPANavigationPropertyInfoAccess navigationInfo) {
this.keyPredicates = navigationInfo.getKeyPredicates();
this.association = navigationInfo.getAssociationPath();
this.uriResource = navigationInfo.getUriResource();
return this;
}
public JPANavigationFilterQueryBuilder setParent(final JPAAbstractQuery parent) {
this.parent = parent;
return this;
}
public JPANavigationFilterQueryBuilder setEntityManager(final EntityManager em) {
this.em = em;
return this;
}
public JPANavigationFilterQueryBuilder setExpression(final VisitableExpression expression) {
this.expression = expression;
return this;
}
public JPANavigationFilterQueryBuilder setFrom(final From<?, ?> from) {
this.from = from;
return this;
}
public JPANavigationFilterQueryBuilder setClaimsProvider(final JPAODataClaimProvider claimsProvider) {
this.claimsProvider = Optional.ofNullable(claimsProvider);
return this;
}
public JPANavigationFilterQueryBuilder setClaimsProvider(final Optional<JPAODataClaimProvider> claimsProvider) {
this.claimsProvider = claimsProvider;
return this;
}
public JPANavigationFilterQueryBuilder setGroups(final List<String> groups) {
this.groups = groups;
return this;
}
boolean asInQuery() throws ODataJPAFilterException {
try {
return (cb instanceof ProcessorCriteriaBuilder
|| association.getLeftColumnsList().size() == 1)
&& getAggregationType(expression) != null;
} catch (final ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private UriResourceKind getAggregationType(final VisitableExpression expression) {
UriInfoResource member = null;
if (expression instanceof final Binary binary) {
if (binary.getLeftOperand() instanceof final JPAMemberOperator leftMember)
member = leftMember.getMember().getResourcePath();
else if (binary.getRightOperand() instanceof final JPAMemberOperator rightMember)
member = rightMember.getMember().getResourcePath();
} else if (expression instanceof JPAFilterExpression
|| expression instanceof JPACountExpression) {
member = ((JPAVisitableExpression) expression).getMember();
}
if (member != null) {
for (final UriResource r : member.getUriResourceParts()) {
if (r.getKind() == UriResourceKind.count)
return r.getKind();
}
}
return null;
}
private boolean isNullExpression(final VisitableExpression expression) {
return expression instanceof final JPANullExpression nullExpression
&& NULL.equals(nullExpression.getLiteral().getText());
}
private JPAEntityType determineEntityType(final JPAAssociationPath associationPath) {
return (JPAEntityType) associationPath.getTargetType();
}
private JPAEntityType asJPAEntityType(final EdmEntityType edmEntityType) throws ODataJPAQueryException {
try {
return sd.getEntity(edmEntityType);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationNullQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationNullQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
/**
* Generates sub queries to be used with an EXISTS condition to fulfill null checks on <i>to one</i> association like
* <i>AdministrativeDivisions?$filter=Parent eq null</i>
* <p>
* EXISTS is preferred over IN, as it showed equal or better performance on PostgreSQL and SAP HANA
* @author Oliver Grande
* @since 1.1.1
* 20.11.2023
*/
public final class JPANavigationNullQuery extends JPANavigationSubQuery implements ExistsExpressionValue {
JPANavigationNullQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType type,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final Optional<JPAODataClaimProvider> claimsProvider,
final List<UriParameter> keyPredicates) throws ODataApplicationException {
super(odata, sd, type, em, parent, from, association, claimsProvider, keyPredicates);
}
/**
* Creates a exist sub query including the where clause joining this query with the parent query
*/
@Override
@SuppressWarnings("unchecked")
public <T extends Object> Subquery<T> getSubQuery(final Subquery<?> childQuery,
final VisitableExpression expression, final List<Path<Comparable<?>>> inPath) throws ODataApplicationException {
if (childQuery != null)
// A count query should be the last in a chain. Therefore childQuery has to be null
throw new ODataJPAQueryException(QUERY_PREPARATION_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR);
if (this.association.getJoinTable() != null) {
createSubQueryJoinTableNull();
} else {
createSubQueryNull((Subquery<T>) this.subQuery);
}
return (Subquery<T>) subQuery;
}
/**
* Example SQL query generated:
*
* <pre>
* SELECT *
* FROM "OLINGO"."AdministrativeDivision" E0
* WHERE EXISTS (
* SELECT E2."CodePublisher" S0
* FROM "OLINGO"."AdministrativeDivision" E2
* WHERE (((E0."ParentDivisionCode" = E2."DivisionCode")
* AND (E0."ParentCodeID" = E2."CodeID"))
* AND (E0."CodePublisher" = E2."CodePublisher"))
* GROUP BY E2."CodePublisher", E2."CodeID", E2."DivisionCode")
* </pre>
*
* @param <T>
* @param childQuery
* @param query
* @throws ODataApplicationException
*/
private <T> void createSubQueryNull(final Subquery<T> query)
throws ODataApplicationException {
createSelectClauseJoin(query, queryRoot, determineAggregationRightColumns(), false);
Expression<Boolean> whereCondition =
createWhereByAssociation(from, queryRoot, determineJoinColumns());
whereCondition = addWhereClause(whereCondition,
createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot));
query.where(whereCondition);
try {
createGroupBy(query, queryRoot, association.getJoinColumnsList());
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_RESULT_NAVI_PROPERTY_UNKNOWN,
HttpStatusCode.INTERNAL_SERVER_ERROR, e, association.getAlias());
}
}
/**
* Example SQL query generated:
*
* <pre>
* SELECT E0."SourceKey" S0, E0."Number" S1
* FROM "OLINGO"."JoinSource" E0
* WHERE EXISTS (SELECT E2."SourceID" S0
* FROM "OLINGO"."JoinRelation" E2
* INNER JOIN "OLINGO"."JoinTarget" E3
* ON (E2."TargetID" = E3."TargetKey")
* WHERE (E2."SourceID" = E0."SourceKey")
* GROUP BY E2."SourceID")
* </pre>
*/
private void createSubQueryJoinTableNull() throws ODataApplicationException {
try {
final List<JPAOnConditionItem> left = association
.getJoinTable()
.getJoinColumns(); // Person -->
final List<JPAOnConditionItem> right = association
.getJoinTable()
.getInverseJoinColumns(); // Person -->
createSelectClauseAggregation(subQuery, queryJoinTable, left, true);
Expression<Boolean> whereCondition = createWhereByAssociation(from, queryJoinTable, left);
whereCondition = addWhereClause(whereCondition, createWhereByAssociation(queryJoinTable, queryRoot, right));
whereCondition = addWhereClause(whereCondition, createProtectionWhereForEntityType(claimsProvider, jpaEntity,
queryRoot));
subQuery.where(whereCondition);
createGroupBy(subQuery, queryJoinTable, left);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExtension.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExtension.java | package com.sap.olingo.jpa.processor.core.query;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
public interface JPAExtension {
/**
* Process a expand query, which contains a $skip and/or a $top option.<p>
* This a tricky problem, as it can not be done easily with SQL. It could be that a database offers special solutions.
* There is an worth reading blog regards this topic:
* <a href="http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/">How to select
* the first/least/max row per group in SQL</a>
* @return query result
*/
JPAExpandResult executeExpandTopSkipQuery();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAQueryCreationResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAQueryCreationResult.java | package com.sap.olingo.jpa.processor.core.query;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
record JPAQueryCreationResult(TypedQuery<Tuple> query, SelectionPathInfo<JPAPath> selection) {
@Override
public String toString() {
return "JPAQueryCreationResult [query=" + query + ", selection=" + selection + "]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractSubQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractSubQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.AbstractQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterElementComplier;
public abstract class JPAAbstractSubQuery extends JPAAbstractQuery {
protected From<?, ?> queryJoinTable = null;
protected Subquery<?> subQuery;
protected final JPAAbstractQuery parentQuery;
protected UriResourceKind aggregationType;
protected From<?, ?> queryRoot = null;
protected final From<?, ?> from;
protected final JPAAssociationPath association;
protected JPAFilterElementComplier filterComplier;
protected final boolean isCollectionProperty;
JPAAbstractSubQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntity,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final Optional<JPAODataClaimProvider> claimsProvider) {
super(odata, sd, jpaEntity, em, claimsProvider);
this.parentQuery = parent;
this.from = from;
this.association = association;
this.isCollectionProperty = toCollectionProperty();
}
JPAAbstractSubQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntity,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association) {
this(odata, sd, jpaEntity, em, parent, from, association, Optional.empty());
}
public abstract <T extends Object> Subquery<T> getSubQuery(final Subquery<?> childQuery,
@Nullable VisitableExpression expression, List<Path<Comparable<?>>> inPath) throws ODataApplicationException;
@SuppressWarnings("unchecked")
@Override
public <T> AbstractQuery<T> getQuery() {
return (AbstractQuery<T>) subQuery;
}
@Override
protected Locale getLocale() {
return locale;
}
@Override
JPAODataRequestContextAccess getContext() {
return parentQuery.getContext();
}
protected void createRoots(final JPAAssociationPath association) throws ODataJPAQueryException {
if (association != null && association.hasJoinTable()) {
if (isCollectionProperty) {
if (association.getTargetType() != null)
this.queryRoot = subQuery.from(association.getTargetType().getTypeClass());
else
this.queryRoot = createCollectionRoot();
} else if (association.getJoinTable().getEntityType() != null) {
createJoinTableRoot(association);
} else {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_NOT_IMPLEMENTED,
HttpStatusCode.NOT_IMPLEMENTED, association.getAlias());
}
} else {
this.queryRoot = subQuery.from(this.jpaEntity.getTypeClass());
}
}
private From<?, ?> createCollectionRoot() {
From<?, ?> join = subQuery.from(association.getSourceType().getTypeClass());
for (final JPAElement element : association.getPath()) {
join = join.join(element.getInternalName());
if (element instanceof JPACollectionAttribute) {
break;
}
}
return join;
}
void createJoinTableRoot(final JPAAssociationPath association) {
// At least for EclipseLink the order is of importance. First the join table has to be mentioned. It becomes
// the "leading" table. Otherwise EclipseLink replaces the join table within the WHERE clause.
this.queryJoinTable = subQuery.from(association.getJoinTable().getEntityType().getTypeClass());
this.queryRoot = subQuery.from(this.jpaEntity.getTypeClass());
}
protected <T> void createSelectClauseAggregation(final Subquery<T> subQuery, final From<?, ?> from,
final List<JPAOnConditionItem> conditionItems, final boolean forInExpression) {
final List<Selection<?>> selections = new ArrayList<>();
for (final JPAOnConditionItem item : conditionItems) {
selections.add(ExpressionUtility.convertToCriteriaPath(from, item.getRightPath().getPath()));
}
setSelection(subQuery, forInExpression, selections);
}
protected <T> void createSelectClauseJoin(final Subquery<T> subQuery, final From<?, ?> from,
final List<JPAPath> conditionItems, final boolean forInExpression) {
final List<Selection<?>> selections = new ArrayList<>();
for (final JPAPath item : conditionItems) {
selections.add(ExpressionUtility.convertToCriteriaPath(from, item.getPath()));
}
setSelection(subQuery, forInExpression, selections);
}
@SuppressWarnings("unchecked")
private <T> void setSelection(final Subquery<T> subQuery, final boolean forInExpression,
final List<Selection<?>> selections) {
if (forInExpression && selections.size() > 1)
try {
((ProcessorSubquery<T>) subQuery).multiselect(selections);
} catch (final ClassCastException e) {
throw new IllegalStateException(
"IN Clause with multiple attributes only supported with criteria builder extension e.g. odata-jpa-processor-cb");
}
else
subQuery.select((Expression<T>) selections.get(0));
}
protected Expression<Boolean> createWhereByAssociation(final From<?, ?> subRoot, final From<?, ?> parentFrom,
final List<JPAOnConditionItem> conditionItems) {
Expression<Boolean> whereCondition = null;
for (final JPAOnConditionItem onItem : conditionItems) {
Path<?> parentPath = parentFrom;
Path<?> subPath = subRoot;
for (final JPAElement jpaPathElement : onItem.getRightPath().getPath())
parentPath = parentPath.get(jpaPathElement.getInternalName());
for (final JPAElement jpaPathElement : onItem.getLeftPath().getPath())
subPath = subPath.get(jpaPathElement.getInternalName());
final Expression<Boolean> equalCondition = cb.equal(parentPath, subPath);
if (whereCondition == null)
whereCondition = equalCondition;
else
whereCondition = cb.and(whereCondition, equalCondition);
}
return whereCondition;
}
protected Expression<Boolean> applyAdditionalFilter(final Expression<Boolean> where)
throws ODataApplicationException {
Expression<Boolean> whereCondition = where;
if (filterComplier != null && aggregationType == null)
try {
if (filterComplier.getExpressionMember() != null)
whereCondition = addWhereClause(whereCondition, filterComplier.compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return whereCondition;
}
protected void handleAggregation(final Subquery<?> subQuery, final From<?, ?> groupByRoot,
final List<JPAPath> groupByPath) throws ODataApplicationException {
final List<Expression<?>> groupByList = new ArrayList<>();
if (filterComplier != null && this.aggregationType != null) {
for (final JPAPath onItem : groupByPath) {
final var subPath = ExpressionUtility.convertToCriteriaPath(groupByRoot, onItem.getPath());
groupByList.add(subPath);
}
subQuery.groupBy(groupByList);
try {
subQuery.having(this.filterComplier.compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
protected List<JPAPath> determineAggregationRightColumns() throws ODataJPAQueryException {
try {
final List<JPAPath> conditionItems = association.hasJoinTable()
? association.getJoinTable().getRightColumnsList()
: association.getRightColumnsList();
if (conditionItems.isEmpty())
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_JOIN_NOT_DEFINED,
HttpStatusCode.INTERNAL_SERVER_ERROR, association.getTargetType().getExternalName(), association
.getSourceType().getExternalName());
return conditionItems;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_RESULT_NAVI_PROPERTY_UNKNOWN,
HttpStatusCode.INTERNAL_SERVER_ERROR, e, association.getAlias());
}
}
protected List<JPAPath> determineAggregationLeftColumns() throws ODataJPAQueryException {
try {
final List<JPAPath> conditionItems = association.hasJoinTable()
? association.getJoinTable().getLeftColumnsList()
: association.getLeftColumnsList();
if (conditionItems.isEmpty())
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_JOIN_NOT_DEFINED,
HttpStatusCode.INTERNAL_SERVER_ERROR, association.getTargetType().getExternalName(), association
.getSourceType().getExternalName());
return conditionItems;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_RESULT_NAVI_PROPERTY_UNKNOWN,
HttpStatusCode.INTERNAL_SERVER_ERROR, e, association.getAlias());
}
}
public abstract List<Path<Comparable<?>>> getLeftPaths() throws ODataJPAIllegalAccessException;
final boolean toCollectionProperty() {
final var path = association.getPath();
return path.get(path.size() - 1) instanceof JPACollectionAttribute;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAConvertibleResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAConvertibleResult.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
public interface JPAConvertibleResult {
/**
*
* @param converter
* @return
* @throws ODataApplicationException
*/
Map<String, JPAEntityCollectionExtension> asEntityCollection(final JPAResultConverter converter)
throws ODataApplicationException;
void putChildren(final Map<JPAAssociationPath, JPAExpandResult> childResults) throws ODataApplicationException;
default JPAEntityCollectionExtension getEntityCollection(final String key, final JPAResultConverter converter,
final JPAAssociationPath association, final List<JPAODataPageExpandInfo> expandInfo)
throws ODataApplicationException {
throw new IllegalAccessError("Not supported");
}
/**
* Returns a key pair if the query had $top and/or $skip and the key of the entity implements {@link Comparable}.
* @param <T>
* @param requestContext
* @param hops
* @return
* @throws ODataJPAQueryException
*/
default Optional<JPAKeyBoundary> getKeyBoundary(final JPAODataRequestContextAccess requestContext,
final List<JPANavigationPropertyInfo> hops) throws ODataJPAProcessException {
return Optional.empty();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinCountQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandJoinCountQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static java.util.Collections.emptyMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
/**
* Requires Processor Query
*
* @author Oliver Grande
* @since 1.0.1
* 25.11.2020
*/
public final class JPAExpandJoinCountQuery extends JPAAbstractExpandJoinQuery implements JPAExpandCountQuery {
public JPAExpandJoinCountQuery(final OData odata,
final JPAODataRequestContextAccess requestContext, final JPAEntityType et,
final JPAAssociationPath association, final List<JPANavigationPropertyInfo> hops,
final Optional<JPAKeyBoundary> keyBoundary)
throws ODataException {
super(odata, requestContext, et, association, copyHops(hops), keyBoundary);
}
public JPAExpandJoinCountQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAExpandItemInfo item, final Optional<JPAKeyBoundary> keyBoundary) throws ODataException {
super(odata, requestContext, item, keyBoundary);
}
@Override
public final Map<String, Long> count() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "count")) {
if (countRequested(lastInfo)) {
final CriteriaQuery<Tuple> countQuery = cb.createTupleQuery();
createCountFrom(countQuery);
final List<Selection<?>> selectionPath = createSelectClause(target);
countQuery.multiselect(addCount(selectionPath));
final jakarta.persistence.criteria.Expression<Boolean> whereClause = createWhere();
if (whereClause != null)
countQuery.where(whereClause);
countQuery.groupBy(extractPath(selectionPath));
final TypedQuery<Tuple> query = em.createQuery(countQuery);
final List<Tuple> intermediateResult = query.getResultList();
return convertCountResult(intermediateResult);
}
return emptyMap();
}
}
private List<Expression<?>> extractPath(final List<Selection<?>> selectionPath) {
final List<Expression<?>> result = new ArrayList<>(selectionPath.size());
for (final var selection : selectionPath) {
if (selection instanceof final Path<?> path) {
result.add(path);
}
}
return result;
}
private void createCountFrom(final CriteriaQuery<Tuple> countQuery) throws ODataApplicationException {
final HashMap<String, From<?, ?>> joinTables = new HashMap<>();
// 1. Create navigation joins
createFromClauseRoot(countQuery, joinTables);
target = root;
createFromClauseNavigationJoins(joinTables);
lastInfo.setFromClause(target);
}
private List<Selection<?>> createSelectClause(final From<?, ?> from) throws ODataApplicationException {
if (association.hasJoinTable()) {
return createAdditionSelectionForJoinTable(association);
} else {
return buildExpandJoinPath(from);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.MISSING_CLAIM;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.MISSING_CLAIMS_PROVIDER;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ORDER_BY_NOT_SUPPORTED;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_RESULT_ENTITY_TYPE_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.WILDCARD_UPPER_NOT_SUPPORTED;
import static java.util.stream.Collectors.toList;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.AbstractQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJoinTable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterComplier;
import com.sap.olingo.jpa.processor.core.processor.JPAEmptyDebugger;
import com.sap.olingo.jpa.processor.core.properties.JPAOrderByPropertyFactory;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
public abstract class JPAAbstractQuery {
protected static final String PERMISSIONS_REGEX = ".*[\\*\\%\\+\\_].*";
protected static final String SELECT_ITEM_SEPARATOR = ",";
protected static final String SELECT_ALL = "*";
protected static final String ROW_NUMBER_COLUMN_NAME = "rowNumber";
protected static final String COUNT_COLUMN_NAME = "\"$count\"";
protected final EntityManager em;
protected final CriteriaBuilder cb;
protected final JPAEntityType jpaEntity; // Entity type of the result, which may not be the same as the start of a
// navigation
protected final JPAServiceDocument sd;
protected JPAServiceDebugger debugger;
protected final OData odata;
protected Locale locale;
protected final Optional<JPAODataClaimProvider> claimsProvider;
protected final List<String> groups;
JPAAbstractQuery(final OData odata, final JPAServiceDocument sd, final EdmEntityType edmEntityType,
final EntityManager em, final Optional<JPAODataClaimProvider> claimsProvider) throws ODataApplicationException {
this(odata, sd, asJPAEntityType(sd, edmEntityType), em, claimsProvider);
}
JPAAbstractQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntityType,
final EntityManager em, final Optional<JPAODataClaimProvider> claimsProvider) {
super();
this.em = em;
this.cb = em.getCriteriaBuilder();
this.sd = sd;
this.jpaEntity = jpaEntityType;
this.debugger = new JPAEmptyDebugger();
this.odata = odata;
this.claimsProvider = claimsProvider;
this.groups = Collections.emptyList();
}
JPAAbstractQuery(final OData odata, final JPAEntityType jpaEntityType,
final JPAODataRequestContextAccess requestContext) throws ODataException {
super();
final Optional<JPAODataGroupProvider> groupsProvider = requestContext.getGroupsProvider();
this.em = requestContext.getEntityManager();
this.cb = em.getCriteriaBuilder();
this.sd = requestContext.getEdmProvider().getServiceDocument();
this.jpaEntity = jpaEntityType;
this.debugger = requestContext.getDebugger();
this.odata = odata;
this.claimsProvider = requestContext.getClaimsProvider();
this.groups = groupsProvider.isPresent() ? groupsProvider.get().getGroups() : Collections.emptyList();
}
public JPAServiceDebugger getDebugger() {
return debugger;
}
/**
*
* @param <T> the type of the result
* @return
*/
public abstract <T> AbstractQuery<T> getQuery();
public abstract <S, T> From<S, T> getRoot();
protected static JPAEntityType asJPAEntityType(final JPAServiceDocument sd, final EdmEntityType edmEntityType)
throws ODataJPAQueryException {
try {
return sd.getEntity(edmEntityType);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
protected Expression<Boolean> addWhereClause(Expression<Boolean> whereCondition,
final Expression<Boolean> additionalExpression) {
if (additionalExpression != null) {
if (whereCondition == null) {
whereCondition = additionalExpression;
} else {
whereCondition = cb.and(whereCondition, additionalExpression);
}
}
return whereCondition;
}
protected Expression<Boolean> orWhereClause(Expression<Boolean> whereCondition,
final Expression<Boolean> additionalExpression) {
if (additionalExpression != null) {
if (whereCondition == null) {
whereCondition = additionalExpression;
} else {
whereCondition = cb.or(whereCondition, additionalExpression);
}
}
return whereCondition;
}
protected final void createFromClauseDescriptionFields(final Collection<JPAPath> selectionPath,
final Map<String, From<?, ?>> joinTables, final From<?, ?> from,
final List<JPANavigationPropertyInfo> navigationInfo)
throws ODataApplicationException {
final List<JPAPath> descriptionFields = extractDescriptionAttributes(selectionPath);
for (final JPANavigationPropertyInfo info : navigationInfo) {
generateDescriptionJoin(joinTables,
determineAllDescriptionPath(info.getFromClause() == from ? descriptionFields : Collections.emptyList(),
info.getFilterCompiler()), info.getFromClause());
}
}
/**
* Add from clause that is needed for orderby clauses that are not part of the navigation part e.g.
* <code>"Organizations?$orderby=Roles/$count desc,Address/Region desc"</code>
* @param orderByTarget
* @param joinTables
*/
protected void createFromClauseOrderBy(final List<JPAProcessorAttribute> orderByTarget,
final Map<String, From<?, ?>> joinTables, final From<?, ?> from) {
orderByTarget.stream()
.map(property -> property.setTarget(from, joinTables, cb))
.filter(JPAProcessorAttribute::requiresJoin)
.forEach(property -> joinTables.put(property.getAlias(), property.createJoin()));
}
protected List<jakarta.persistence.criteria.Expression<?>> createGroupBy(final Map<String, From<?, ?>> joinTables, // NOSONAR
final From<?, ?> from, final Collection<JPAPath> selectionPathList, @Nonnull final Set<Path<?>> orderByPaths) {
try (JPARuntimeMeasurement serializerMeasurement = debugger.newMeasurement(this, "createGroupBy")) {
final List<jakarta.persistence.criteria.Expression<?>> groupBy = new ArrayList<>();
for (final JPAPath jpaPath : selectionPathList) {
final var path = ExpressionUtility.convertToCriteriaPath(joinTables, from, jpaPath);
orderByPaths.remove(path);
groupBy.add(path);
}
for (final var path : orderByPaths) {
groupBy.add(path);
}
return groupBy;
}
}
protected List<jakarta.persistence.criteria.Expression<?>> createGroupBy(final Map<String, From<?, ?>> joinTables,
final From<?, ?> from, final Collection<JPAPath> selectionPathList,
@Nonnull final List<JPAProcessorAttribute> orderByAttributes) {
try (JPARuntimeMeasurement serializerMeasurement = debugger.newMeasurement(this, "createGroupBy")) {
final Set<Path<?>> orderByPaths = new HashSet<>();
final List<jakarta.persistence.criteria.Expression<?>> groupBy = new ArrayList<>();
for (final JPAPath jpaPath : selectionPathList) {
final var path = ExpressionUtility.convertToCriteriaPath(joinTables, from, jpaPath);
orderByPaths.add(path);
groupBy.add(path);
}
for (final var attribute : orderByAttributes) {
final var path = attribute.getPath();
if (path != null && !orderByPaths.contains(path))
groupBy.add(path);
}
return groupBy;
}
}
protected <T, S> Join<T, S> createJoinFromPath(final String alias, final List<JPAElement> pathList,
final From<T, S> root, final JoinType finalJoinType) {
Join<T, S> join = null;
JoinType joinType;
for (int i = 0; i < pathList.size(); i++) {
if (i == pathList.size() - 1) {
joinType = finalJoinType;
} else {
joinType = JoinType.INNER;
}
if (i == 0) {
join = root.join(pathList.get(i).getInternalName(), joinType);
join.alias(alias);
} else if (i < pathList.size()) {
join = join.join(pathList.get(i).getInternalName(), joinType);
join.alias(pathList.get(i).getExternalName());
}
}
return join;
}
/**
* The value of the $select query option is a comma-separated list of <b>properties</b>, qualified action names,
* qualified function names, the <b>star operator (*)</b>, or the star operator prefixed with the namespace or alias
* of the schema in order to specify all operations defined in the schema. See:
* <a
* href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398297"
* >OData Version 4.0 Part 1 - 11.2.4.1 System Query Option $select</a>
* <p>
* See also:
* <a
* href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398163"
* >OData Version 4.0 Part 2 - 5.1.3 System Query Option $select</a>
*
* @param joinTables
* @param requestedProperties
* @param optional
* @return
* @throws ODataApplicationException
*/
protected List<Selection<?>> createSelectClause(final Map<String, From<?, ?>> joinTables, // NOSONAR
final Collection<JPAPath> requestedProperties, final From<?, ?> target, final List<String> groups)
throws ODataApplicationException { // NOSONAR Allow subclasses to throw an exception
try (JPARuntimeMeasurement serializerMeasurement = debugger.newMeasurement(this, "createSelectClause")) {
final List<Selection<?>> selections = new ArrayList<>();
// Build select clause
for (final JPAPath jpaPath : requestedProperties) {
if (jpaPath.isPartOfGroups(groups)) {
final Path<?> path = ExpressionUtility.convertToCriteriaPath(joinTables, target, jpaPath);
path.alias(jpaPath.getAlias());
selections.add(path);
}
}
return selections;
}
}
protected Expression<Boolean> createProtectionWhereForEntityType(
final Optional<JPAODataClaimProvider> claimsProvider, final JPAEntityType et, final From<?, ?> from)
throws ODataJPAQueryException {
try {
jakarta.persistence.criteria.Expression<Boolean> restriction = null;
final Map<String, From<?, ?>> dummyJoinTables = new HashMap<>(1);
for (final JPAProtectionInfo protection : et.getProtections()) { // look for protected attributes
final List<JPAClaimsPair<?>> values = claimsProvider.get().get(protection.getClaimName()); // NOSONAR
if (values.isEmpty()) {
throw new ODataJPAQueryException(MISSING_CLAIM, HttpStatusCode.FORBIDDEN);
}
if (!(containsAll(values))) {
final Path<?> path = ExpressionUtility.convertToCriteriaPath(dummyJoinTables, from, protection.getPath());
restriction = addWhereClause(restriction, createProtectionWhereForAttribute(values, path, protection
.supportsWildcards()));
}
}
return restriction;
} catch (final NoSuchElementException e) {
throw new ODataJPAQueryException(MISSING_CLAIMS_PROVIDER, HttpStatusCode.FORBIDDEN);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(QUERY_RESULT_ENTITY_TYPE_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private boolean containsAll(final List<JPAClaimsPair<?>> values) {
return values.stream()
.anyMatch(value -> JPAClaimsPair.ALL.equals(value.min));
}
protected Expression<Boolean> createWhereByKey(final JPANavigationPropertyInfo navigationInfo)
throws ODataJPAModelException, ODataApplicationException {
return createWhereByKey(navigationInfo.getFromClause(), navigationInfo.getKeyPredicates(), navigationInfo
.getEntityType());
}
protected Expression<Boolean> createWhereByKey(final From<?, ?> root,
final List<UriParameter> keyPredicates, final JPAEntityType et) throws ODataApplicationException {
// .../Organizations('3')
// .../BusinessPartnerRoles(BusinessPartnerID='6',RoleCategory='C')
jakarta.persistence.criteria.Expression<Boolean> compoundCondition = null;
if (keyPredicates != null) {
for (final UriParameter keyPredicate : keyPredicates) {
try {
final jakarta.persistence.criteria.Expression<Boolean> equalCondition =
ExpressionUtility.createEQExpression(odata, cb, root, et, keyPredicate);
compoundCondition = addWhereClause(compoundCondition, equalCondition);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.BAD_REQUEST);
}
}
}
return compoundCondition;
}
@SuppressWarnings("unchecked")
protected final Expression<Boolean> createWhereKeyIn(final JPAAssociationPath associationPath,
final From<?, ?> target, final Subquery<?> subQuery) throws ODataJPAQueryException {
try {
final List<Path<Comparable<?>>> paths = (List<Path<Comparable<?>>>) createWhereKeyInPathList(associationPath,
target);
debugger.trace(this, "Creating WHERE snipped for in clause %s", paths);
return ((ProcessorCriteriaBuilder) cb).in(paths, (Subquery<List<Comparable<?>>>) subQuery);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
protected List<?> createWhereKeyInPathList(final JPAAssociationPath associationPath,
final From<?, ?> target) throws ODataJPAModelException {
if (associationPath.hasJoinTable()) {
final JPAJoinTable joinTable = associationPath.getJoinTable();
// jt.getInverseJoinColumns().get(0).getLeftPath()
debugger.trace(this, "Creating WHERE snipped for key in with join conditions %s", joinTable.getJoinColumns());
return joinTable
.getJoinColumns()
.stream()
.map(JPAOnConditionItem::getRightPath)
.map(JPAPath::getLeaf)
.map(leaf -> target.get(leaf.getInternalName()))
.collect(toList()); // NOSONAR
}
return associationPath.getJoinColumnsList().stream()
.map(key -> mapOnToWhere(key, target))
.collect(toList()); // NOSONAR
}
protected final List<JPAPath> extractDescriptionAttributes(final Collection<JPAPath> jpaPathList) {
final List<JPAPath> result = new ArrayList<>();
for (final JPAPath p : jpaPathList) {
if (p.getLeaf() instanceof JPADescriptionAttribute) {
result.add(p);
}
}
return result;
}
protected List<JPAProcessorAttribute> getOrderByAttributes(final OrderByOption orderBy)
throws ODataApplicationException {
if (orderBy != null) {
try {
final var factory = new JPAOrderByPropertyFactory();
final var orderByAttributes = orderBy.getOrders().stream()
.map(o -> factory.createProperty(o, jpaEntity, getLocale()))
.collect(Collectors.toList()); // NOSONAR
for (final var orderByAttribute : orderByAttributes) {
if (!orderByAttribute.isSortable())
throw new ODataJPAQueryException(QUERY_PREPARATION_ORDER_BY_NOT_SUPPORTED, BAD_REQUEST, orderByAttribute
.getAlias());
}
return orderByAttributes;
} catch (final ODataJPAIllegalArgumentException e) {
throw new ODataJPAQueryException(QUERY_PREPARATION_ORDER_BY_NOT_SUPPORTED, BAD_REQUEST, e.getParams());
}
}
return new ArrayList<>();
}
protected void generateDescriptionJoin(final Map<String, From<?, ?>> joinTables, final Set<JPAPath> pathSet,
final From<?, ?> target) {
for (final JPAPath descriptionFieldPath : pathSet) {
final JPADescriptionAttribute descriptionField = ((JPADescriptionAttribute) descriptionFieldPath.getLeaf());
final Join<?, ?> join = createJoinFromPath(descriptionFieldPath.getAlias(), descriptionFieldPath.getPath(),
target, JoinType.LEFT);
if (descriptionField.isLocationJoin()) {
join.on(createOnCondition(join, descriptionField, getLocale().toString()));
} else {
join.on(createOnCondition(join, descriptionField, getLocale().getLanguage()));
}
joinTables.put(descriptionFieldPath.getAlias(), join);
}
}
protected abstract Locale getLocale();
public JPAEntityType getJpaEntity() {
return jpaEntity;
}
Set<JPAPath> determineAllDescriptionPath(final List<JPAPath> descriptionFields,
final JPAFilterComplier filter) throws ODataApplicationException {
final Set<JPAPath> allPath = new HashSet<>(descriptionFields);
if (filter != null) {
for (final JPAPath path : filter.getMember()) {
if (path.getLeaf() instanceof JPADescriptionAttribute) {
allPath.add(path);
}
}
}
return allPath;
}
abstract JPAODataRequestContextAccess getContext();
@SuppressWarnings({ "unchecked" })
private <Y extends Comparable<? super Y>> Predicate createBetween(final JPAClaimsPair<?> value, final Path<?> path) {
return cb.between((jakarta.persistence.criteria.Expression<? extends Y>) path, (Y) value.min, (Y) value.max);
}
private Expression<Boolean> createOnCondition(final Join<?, ?> join, final JPADescriptionAttribute descriptionField,
final String localValue) {
final Predicate existingOn = join.getOn();
Expression<Boolean> result = cb.equal(determineLocalePath(join, descriptionField.getLocaleFieldName()), localValue);
if (existingOn != null) {
result = cb.and(existingOn, result);
}
for (final JPAPath value : descriptionField.getFixedValueAssignment().keySet()) {
result = cb.and(result,
cb.equal(determineLocalePath(join, value), descriptionField.getFixedValueAssignment().get(value)));
}
return result;
}
@SuppressWarnings("unchecked")
private Expression<Boolean> createProtectionWhereForAttribute(final List<JPAClaimsPair<?>> values, final Path<?> path,
final boolean wildcardsSupported) throws ODataJPAQueryException {
jakarta.persistence.criteria.Expression<Boolean> attributeRestriction = null;
for (final JPAClaimsPair<?> value : values) { // for each given claim value
if (value.hasUpperBoundary) {
if (wildcardsSupported && containsWildcard((String) value.min)) {
throw new ODataJPAQueryException(WILDCARD_UPPER_NOT_SUPPORTED, HttpStatusCode.BAD_REQUEST);
} else {
attributeRestriction = orWhereClause(attributeRestriction, createBetween(value, path));
}
} else {
if (wildcardsSupported && containsWildcard((String) value.min)) {
attributeRestriction = orWhereClause(attributeRestriction, cb.like((Path<String>) path,
((String) value.min).replace('*', '%').replace('+', '_')));
} else {
attributeRestriction = orWhereClause(attributeRestriction, cb.equal(path, value.min));
}
}
}
return attributeRestriction;
}
private boolean containsWildcard(final String min) {
return min.contains("*")
|| min.contains("+")
|| min.contains("%")
|| min.contains("_");
}
private Expression<?> determineLocalePath(final Join<?, ?> join, final JPAPath jpaPath) {
Path<?> path = join;
for (final JPAElement pathElement : jpaPath.getPath()) {
path = path.get(pathElement.getInternalName());
}
return path;
}
private Path<Comparable<?>> mapOnToWhere(final JPAOnConditionItem on, final From<?, ?> target) {
return target.get(on.getRightPath().getLeaf().getInternalName());
}
protected boolean hasRowLimit(final JPANavigationPropertyInfo hop) {
final TopOption top = hop.getUriInfo().getTopOption();
final SkipOption skip = hop.getUriInfo().getSkipOption();
return top != null || skip != null;
}
protected Expression<Boolean> createWhereByRowNumber(final From<?, ?> target, final JPANavigationPropertyInfo hop) {
final Expression<? extends Number> rowNumberPath = target.get(ROW_NUMBER_COLUMN_NAME);
final Optional<TopOption> top = Optional.ofNullable(hop.getUriInfo().getTopOption());
final Optional<SkipOption> skip = Optional.ofNullable(hop.getUriInfo().getSkipOption());
final Integer firstRow = skip.map(SkipOption::getValue).orElse(0);
final Predicate offset = cb.gt(rowNumberPath, firstRow);
final Predicate limit = top
.map(t -> t.getValue() + firstRow)
.map(l -> cb.le(rowNumberPath, l))
.orElse(null);
return addWhereClause(offset, limit);
}
protected Expression<Boolean> createWhereTableJoin(final From<?, ?> joinRoot, final From<?, ?> joinTable,
final JPAAssociationPath association, final boolean useInverse) throws ODataJPAQueryException {
if (association.hasJoinTable()) {
try {
final JPAJoinTable jpaJoinTable = association.getJoinTable();
final List<JPAOnConditionItem> joinColumns = useInverse ? jpaJoinTable.getInverseJoinColumns() : jpaJoinTable
.getJoinColumns();
debugger.trace(this, "Creating WHERE snipped for join table %s with join conditions %s and inverse: %s",
jpaJoinTable.toString(), joinColumns, useInverse);
debugger.trace(this, "Creating WHERE snipped for join table, with target: '%s', root: '%s'", joinTable
.getJavaType(), joinRoot.getJavaType());
Expression<Boolean> whereCondition = null;
for (final JPAOnConditionItem jc : joinColumns) {
final String leftColumn = jc.getLeftPath().getLeaf().getInternalName();
final String rightColumn = jc.getRightPath().getLeaf().getInternalName();
final Path<?> left = useInverse ? joinRoot.get(leftColumn) : joinRoot.get(rightColumn);
final Path<?> right = useInverse ? joinTable.get(rightColumn) : joinTable.get(leftColumn);
whereCondition = addWhereClause(whereCondition, cb.equal(left, right));
}
return whereCondition;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
return null;
}
/**
* Any resource path or path expression identifying a collection of entities or complex type instances can be appended
* with a path segment containing the qualified name of a type derived from the declared type of the collection.</br>
* The use of the unqualified name of a derived type is <b>not</b> supported.
* <p>
* See also:
* <a href="
* https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#sec_AddressingDerivedTypes">
* 4.11 Addressing Derived Types
* </a>
*
* @param baseType
* @param potentialDerivedType
* @return true if potentialDerivedType is indeed a derived type of baseType
* @throws ODataJPAModelException
*/
boolean derivedTypeRequested(@Nonnull final JPAStructuredType baseType,
@Nonnull final JPAStructuredType potentialDerivedType) throws ODataJPAModelException {
JPAStructuredType type = potentialDerivedType;
while (type != null && type.getBaseType() != null) {
if (baseType.equals(type.getBaseType()))
return true;
type = type.getBaseType();
}
return false;
}
/**
* Add key restrictions as well as the filter enhancement from the entity definition from superordinate entities
* @param info
* @return
* @throws ODataApplicationException
*/
protected final Expression<Boolean> createKeyWhere(final List<JPANavigationPropertyInfo> info)
throws ODataApplicationException {
Expression<Boolean> whereCondition = null;
// Given key: Organizations('1')/Roles(...)
for (final JPANavigationPropertyInfo naviInfo : info) {
try {
final JPAEntityType et = naviInfo.getEntityType();
final From<?, ?> from = naviInfo.getFromClause();
if (naviInfo.getKeyPredicates() != null) {
final List<UriParameter> keyPredicates = naviInfo.getKeyPredicates();
whereCondition = addWhereClause(whereCondition, createWhereByKey(from, keyPredicates, et));
}
whereCondition = addWhereClause(whereCondition, createWhereEnhancement(et, from));
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
return whereCondition;
}
protected abstract Expression<Boolean> createWhereEnhancement(final JPAEntityType et, final From<?, ?> from)
throws ODataJPAProcessorException;
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandQuery.java | package com.sap.olingo.jpa.processor.core.query;
import org.apache.olingo.server.api.ODataApplicationException;
public interface JPAExpandQuery {
JPAExpandQueryResult execute() throws ODataApplicationException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/EdmBindingTargetResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/EdmBindingTargetResult.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding;
import org.apache.olingo.server.api.uri.UriParameter;
/**
* Container to provide result e.g. of target entity set or singleton determination
* @author Oliver Grande
*
*/
final class EdmBindingTargetResult implements EdmBindingTargetInfo {
private final EdmBindingTarget edmBindingTarget;
private final List<UriParameter> keyPredicates;
private final String navigationPath;
EdmBindingTargetResult(final EdmBindingTarget targetEdmBindingTarget, final List<UriParameter> keyPredicates,
final String navigationPath) {
super();
this.edmBindingTarget = targetEdmBindingTarget;
this.keyPredicates = keyPredicates;
this.navigationPath = navigationPath;
}
@Override
public EdmBindingTarget getEdmBindingTarget() {
return this.edmBindingTarget;
}
@Override
public List<UriParameter> getKeyPredicates() {
return this.keyPredicates;
}
@Override
public String getName() {
return edmBindingTarget.getName();
}
@Override
public String getNavigationPath() {
return navigationPath;
}
@Override
public EdmBindingTarget getTargetEdmBindingTarget() {
if (navigationPath == null || navigationPath.isEmpty())
return this.edmBindingTarget;
else {
for (final EdmNavigationPropertyBinding navigation : this.edmBindingTarget.getNavigationPropertyBindings()) {
if (navigation.getPath().equals(navigationPath))
return edmBindingTarget.getEntityContainer().getEntitySet(navigation.getTarget());
}
return this.edmBindingTarget;
}
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACountQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACountQuery.java | package com.sap.olingo.jpa.processor.core.query;
import org.apache.olingo.server.api.ODataApplicationException;
public interface JPACountQuery {
/**
* Fulfill $count requests. For details see
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752288"
* >OData Version 4.0 Part 1 - 11.2.5.5 System Query Option $count</a>
* @return
* @throws ODataApplicationException
*/
Long countResults() throws ODataApplicationException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForInQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationCountForInQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAInvertibleVisitableExpression;
public class JPANavigationCountForInQuery extends JPANavigationCountQuery implements InExpressionValue {
private Optional<List<Path<Comparable<?>>>> leftPaths;
JPANavigationCountForInQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType type,
final EntityManager em,
final JPAAbstractQuery parent, final From<?, ?> from, final JPAAssociationPath association,
final Optional<JPAODataClaimProvider> claimsProvider, final List<UriParameter> keyPredicates)
throws ODataApplicationException {
super(odata, sd, type, em, parent, from, association, claimsProvider, keyPredicates);
leftPaths = Optional.empty();
}
@Override
protected void createSubQueryCollectionProperty() throws ODataApplicationException {
if (association.getTargetType() == null) {
createSubQueryCollectionNoTargetType();
} else {
createSubQueryCollectionWithTargetType();
}
}
/**
* <pre>
* WHERE t0."ID" IN (
* SELECT t5."ParentID"
* FROM "OLINGO"."InhouseAddress" t5
* WHERE (t5."ParentID" IS NOT NULL)
* GROUP BY t5."ParentID"
* HAVING (COUNT(t5."ParentID") = 2))
* </pre>
*/
private void createSubQueryCollectionWithTargetType() throws ODataApplicationException {
try {
final var right = association.getJoinTable().getInverseJoinColumns();
createSelectClauseAggregation(subQuery, queryRoot, right, true);
leftPaths = Optional.of(ExpressionUtility.convertToCriteriaPaths(from, determineAggregationLeftColumns()));
Expression<Boolean> whereCondition = createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot);
whereCondition = addWhereClause(whereCondition, createNullCheckRight(queryRoot, right));
whereCondition = applyAdditionalFilter(whereCondition);
if (whereCondition != null)
subQuery.where(whereCondition);
createGroupBy(subQuery, queryRoot, right);
createHaving(subQuery);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private void createSubQueryCollectionNoTargetType() throws ODataApplicationException {
try {
final var left = association.getLeftColumnsList();
createSelectClauseJoin(subQuery, queryRoot, left, true);
leftPaths = Optional.of(ExpressionUtility.convertToCriteriaPaths(from, left));
Expression<Boolean> whereCondition = createProtectionWhereForEntityType(claimsProvider,
(JPAEntityType) association.getSourceType(), queryRoot);
whereCondition = addWhereClause(whereCondition, createNullCheck(queryRoot, left));
whereCondition = applyAdditionalFilter(whereCondition);
if (whereCondition != null)
subQuery.where(whereCondition);
handleAggregation(subQuery, queryRoot, left);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* <pre>
* WHERE (t0."CodePublisher", t0."CodeID", t0."DivisionCode") IN (
* SELECT t1."CodePublisher",t1."ParentCodeID", t1."ParentDivisionCode"
* FROM "OLINGO"."AdministrativeDivision" t1
* GROUP BY t1."CodePublisher", t1."ParentCodeID", t1."ParentDivisionCode"
* HAVING (COUNT(t1."DivisionCode") >= 1) )
* </pre>
*/
@Override
protected <T> void createSubQueryAggregation(final Subquery<T> query) throws ODataApplicationException {
final var aggregationColumns = determineAggregationRightColumns();
createSelectClauseJoin(query, queryRoot, aggregationColumns, true);
leftPaths = Optional.of(ExpressionUtility.convertToCriteriaPaths(from, determineAggregationLeftColumns()));
Expression<Boolean> whereCondition = createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot);
whereCondition = addWhereClause(whereCondition, createNullCheck(queryRoot, aggregationColumns));
whereCondition = applyAdditionalFilter(whereCondition);
if (whereCondition != null)
query.where(whereCondition);
handleAggregation(query, queryRoot, aggregationColumns);
}
/**
* <pre>
* WHERE ((t0."ID") IN (
* SELECT t1."SourceID"
* FROM "OLINGO"."BusinessPartnerRole" t2,
* "OLINGO"."JoinPartnerRoleRelation" t1
* WHERE (((t2."BusinessPartnerID" = t1."SourceID")
* AND (t2."BusinessPartnerRole" = t1."TargetID"))
* AND (t2."BusinessPartnerRole" = 'B'))
* GROUP BY t1."SourceID"
* HAVING (COUNT(t1."SourceID") = 1))
* </pre>
*/
@Override
protected void createSubQueryJoinTableAggregation() throws ODataApplicationException {
try {
final List<JPAOnConditionItem> left = association
.getJoinTable()
.getJoinColumns(); // Person -->
final List<JPAOnConditionItem> right = association
.getJoinTable()
.getInverseJoinColumns(); // Person -->
createSelectClauseAggregation(subQuery, queryJoinTable, left, true);
leftPaths = Optional.of(buildLeftPath(from, left));
Expression<Boolean> whereCondition = createWhereByAssociation(queryJoinTable, queryRoot, right);
whereCondition = addWhereClause(whereCondition,
createProtectionWhereForEntityType(claimsProvider, jpaEntity, queryRoot));
whereCondition = addWhereClause(whereCondition, createNullCheckRight(queryJoinTable, left));
whereCondition = applyAdditionalFilter(whereCondition);
if (whereCondition != null)
subQuery.where(whereCondition);
createGroupBy(subQuery, queryJoinTable, left);
createHaving(subQuery);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private Expression<Boolean> createNullCheckRight(final From<?, ?> joinTable,
final List<JPAOnConditionItem> conditionItems) {
Expression<Boolean> result = null;
for (final JPAOnConditionItem onCondition : conditionItems) {
final var subPath = ExpressionUtility.convertToCriteriaPath(joinTable, onCondition.getRightPath().getPath());
result = addWhereClause(result, cb.isNotNull(subPath));
}
return result;
}
private Expression<Boolean> createNullCheck(final From<?, ?> queryRoot, final List<JPAPath> aggregationColumns) {
Expression<Boolean> result = null;
if (filterComplier.getExpressionMember() instanceof final JPAInvertibleVisitableExpression visitableExpression
&& visitableExpression.isInversionRequired()) {
for (final var column : aggregationColumns) {
final var subPath = ExpressionUtility.convertToCriteriaPath(queryRoot, column.getPath());
result = addWhereClause(result, cb.isNotNull(subPath));
}
}
return result;
}
private List<Path<Comparable<?>>> buildLeftPath(final From<?, ?> from,
final List<JPAOnConditionItem> conditionItems) {
return conditionItems.stream()
.map(item -> ExpressionUtility.<Comparable<?>> convertToCriteriaPath(from, item.getLeftPath().getPath()))
.toList();
}
@Override
public List<Path<Comparable<?>>> getLeftPaths() throws ODataJPAIllegalAccessException {
return leftPaths.orElseThrow(ODataJPAIllegalAccessException::new);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionJoinQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACollectionJoinQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_INVALID_SELECTION_PATH;
import static java.util.stream.Collectors.joining;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public class JPACollectionJoinQuery extends JPAAbstractJoinQuery implements JPAQuery {
private final JPAAssociationPath association;
private final Optional<JPAKeyBoundary> keyBoundary;
public JPACollectionJoinQuery(final OData odata, final JPACollectionItemInfo item,
final JPAODataRequestContextAccess requestContext, final Optional<JPAKeyBoundary> keyBoundary)
throws ODataException {
super(odata, item.getEntityType(), requestContext, new ArrayList<>(item.getHops().subList(0,
item.getHops().size() - 1)));
this.association = item.getExpandAssociation();
this.keyBoundary = keyBoundary;
if (this.cb instanceof final ProcessorCriteriaBuilder processorCb)
processorCb.resetParameterBuffer();
}
@Override
public JPACollectionQueryResult execute() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "executeStandardQuery")) {
final SelectionPathInfo<JPAPath> requestedSelection = buildSelectionPathList(this.uriResource);
final TypedQuery<Tuple> tupleQuery = createTupleQuery(requestedSelection);
List<Tuple> intermediateResult;
try (JPARuntimeMeasurement resultMeasurement = debugger.newMeasurement(this, "getResultList")) {
intermediateResult = tupleQuery.getResultList();
}
final Map<String, List<Tuple>> result = convertResult(intermediateResult, association, 0, Long.MAX_VALUE);
return new JPACollectionQueryResult(result, new HashMap<>(1), jpaEntity, this.association,
requestedSelection.joinedRequested());
} catch (final JPANoSelectionException e) {
return new JPACollectionQueryResult(this.jpaEntity, association, Collections.emptyList());
}
}
@Override
protected SelectionPathInfo<JPAPath> buildSelectionPathList(final UriInfoResource uriResource)
throws ODataApplicationException {
final SelectionPathInfo<JPAPath> jpaPathList = new SelectionPathInfo<>();
final String pathPrefix = Utility.determinePropertyNavigationPrefix(uriResource.getUriResourceParts());
final SelectOption select = uriResource.getSelectOption();
// Following situations have to be handled:
// - .../Organizations --> Select all collection attributes
// - .../Organizations('1')/Comment --> Select navigation target
// - .../Et/St/St --> Select navigation target --> Select navigation target via complex properties
// - .../Organizations?$select=ID,Comment --> Select collection attributes given by select clause
// - .../Persons('99')/InhouseAddress?$select=Building --> Select attributes of complex collection given by select
// clause
try {
if (SelectOptionUtil.selectAll(select))
// If the collection is part of a navigation take all the attributes
expandPath(jpaEntity, jpaPathList, this.association.getAlias(), true);
else {
final var st = jpaEntity;
for (final SelectItem sItem : select.getSelectItems()) {
final JPAPath selectItemPath = selectItemAsPath(st, pathPrefix, sItem);
if (pathContainsCollection(selectItemPath)) {
if (selectItemPath.getLeaf().isComplex()) {
expandPath(st, jpaPathList, selectItemPath.getAlias(), true);
} else {
jpaPathList.getODataSelections().add(selectItemPath);
}
} else if (selectItemPath.getLeaf().isComplex()) {
expandPath(st, jpaPathList, pathPrefix.isEmpty() ? this.association.getAlias() : pathPrefix
+ JPAPath.PATH_SEPARATOR + this.association.getAlias(), true);
}
}
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(QUERY_PREPARATION_INVALID_SELECTION_PATH, BAD_REQUEST);
}
return jpaPathList;
}
private JPAPath selectItemAsPath(final JPAStructuredType st, final String pathPrefix, final SelectItem selectionItem)
throws ODataJPAModelException, ODataJPAQueryException {
String pathItem = selectionItem.getResourcePath().getUriResourceParts().stream()
.map(path -> (path.getSegmentValue()))
.collect(Collectors.joining(JPAPath.PATH_SEPARATOR));
pathItem = pathPrefix == null || pathPrefix.isEmpty() ? pathItem : pathPrefix + JPAPath.PATH_SEPARATOR
+ pathItem;
final JPAPath selectItemPath = st.getPath(pathItem);
if (selectItemPath == null)
throw new ODataJPAQueryException(QUERY_PREPARATION_INVALID_SELECTION_PATH, BAD_REQUEST);
return selectItemPath;
}
@Override
protected List<Selection<?>> createSelectClause(final Map<String, From<?, ?>> joinTables, // NOSONAR
final Collection<JPAPath> jpaPathList, final From<?, ?> target, final List<String> groups)
throws ODataApplicationException { // NOSONAR Allow
// subclasses to throw an exception
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createSelectClause")) {
final List<Selection<?>> selections = new ArrayList<>();
// Based on an error in Eclipse Link first the join columns have to be selected. Otherwise the alias is assigned
// to
// the wrong column. E.g. if Organization Comment shall be read Eclipse Link automatically selects also the Order
// column and if the join column is added later the select clause would look as follows: SELECT t0."Text,
// t0."Order", t1,"ID". Eclipse Link will then return the value of the Order column for the alias of the ID
// column.
createAdditionSelectionForJoinTable(selections);
// Build select clause
for (final JPAPath jpaPath : jpaPathList) {
if (jpaPath.isPartOfGroups(groups)) {
final Path<?> path = ExpressionUtility.convertToCriteriaPath(joinTables, target, jpaPath);
path.alias(jpaPath.getAlias());
selections.add(path);
}
}
return selections;
}
}
/**
* Splits up a expand results, so it is returned as a map that uses a concatenation of the field values know by the
* parent.
*
* @param intermediateResult
* @param associationPath
* @param skip
* @param top
* @return
* @throws ODataApplicationException
*/
Map<String, List<Tuple>> convertResult(final List<Tuple> intermediateResult, final JPAAssociationPath associationPath,
final long skip, final long top) throws ODataApplicationException {
String joinKey = "";
long skipped = 0;
long taken = 0;
List<Tuple> subResult = null;
final Map<String, List<Tuple>> convertedResult = new HashMap<>();
for (final Tuple row : intermediateResult) {
String actualKey;
try {
actualKey = buildConcatenatedKey(row, associationPath);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, BAD_REQUEST);
}
if (!actualKey.equals(joinKey)) {
subResult = new ArrayList<>();
convertedResult.put(actualKey, subResult);
joinKey = actualKey;
skipped = taken = 0;
}
if (skipped >= skip && taken < top && subResult != null) {
taken += 1;
subResult.add(row);
} else {
skipped += 1;
}
}
return convertedResult;
}
private String buildConcatenatedKey(final Tuple row, final JPAAssociationPath associationPath)
throws ODataJPAModelException {
if (!associationPath.hasJoinTable()) {
final List<JPAPath> joinColumns = associationPath.getRightColumnsList();
return joinColumns.stream()
.map(column -> (row.get(column.getAlias())).toString())
.collect(joining(JPAPath.PATH_SEPARATOR));
} else {
final List<JPAPath> joinColumns = associationPath.getLeftColumnsList();
return joinColumns.stream()
.map(column -> (row.get(association.getAlias() + ALIAS_SEPARATOR + column.getAlias())).toString())
.collect(joining(JPAPath.PATH_SEPARATOR));
}
}
private List<Order> createOrderByJoinCondition(final JPAAssociationPath associationPath)
throws ODataApplicationException {
final List<Order> orders = new ArrayList<>();
try {
final List<JPAPath> joinColumns = associationPath.hasJoinTable()
? associationPath.getLeftColumnsList() : associationPath.getRightColumnsList();
final From<?, ?> from = associationPath.hasJoinTable()
? determineParentFrom() : target;
for (final JPAPath j : joinColumns) {
Path<?> jpaProperty = from;
for (final JPAElement pathElement : j.getPath()) {
jpaProperty = jpaProperty.get(pathElement.getInternalName());
}
orders.add(cb.asc(jpaProperty));
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, BAD_REQUEST);
}
return orders;
}
private TypedQuery<Tuple> createTupleQuery(final SelectionPathInfo<JPAPath> selectionPath)
throws ODataApplicationException,
JPANoSelectionException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createTupleQuery")) {
final Map<String, From<?, ?>> joinTables = createFromClause(new ArrayList<>(1),
selectionPath.joinedPersistent(), cq, lastInfo);
// TODO handle Join Column is ignored
cq.multiselect(createSelectClause(joinTables, selectionPath.joinedPersistent(), target, groups));
cq.distinct(true);
final jakarta.persistence.criteria.Expression<Boolean> whereClause = createWhere();
if (whereClause != null)
cq.where(whereClause);
final List<Order> orderBy = createOrderByJoinCondition(association);
orderBy.addAll(new JPAOrderByBuilder(jpaEntity, target, cb, groups).createOrderByList(joinTables));
cq.orderBy(orderBy);
return em.createQuery(cq);
}
}
Expression<Boolean> createWhere() throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createWhere")) {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
// Given keys: Organizations('1')/Roles(...)
whereCondition = createKeyWhere(navigationInfo);
whereCondition = addWhereClause(whereCondition, createBoundary(navigationInfo, keyBoundary));
whereCondition = addWhereClause(whereCondition, createCollectionWhere());
whereCondition = addWhereClause(whereCondition, createProtectionWhere(claimsProvider));
return whereCondition;
}
}
private jakarta.persistence.criteria.Expression<Boolean> createCollectionWhere()
throws ODataApplicationException {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
for (final JPANavigationPropertyInfo info : this.navigationInfo) {
if (info.getFilterCompiler() != null) {
try {
whereCondition = addWhereClause(whereCondition, info.getFilterCompiler().compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(QUERY_PREPARATION_FILTER_ERROR, BAD_REQUEST, e);
}
}
}
return whereCondition;
}
private From<?, ?> determineParentFrom() throws ODataJPAQueryException {
for (final JPANavigationPropertyInfo item : this.navigationInfo) {
if (item.getAssociationPath() == association)
return item.getFromClause();
}
throw new ODataJPAQueryException(QUERY_PREPARATION_FILTER_ERROR, BAD_REQUEST);
}
private void createAdditionSelectionForJoinTable(final List<Selection<?>> selections) throws ODataJPAQueryException {
final From<?, ?> parent = determineParentFrom(); // e.g. JoinSource
try {
for (final JPAPath p : association.getLeftColumnsList()) {
final Path<?> selection = ExpressionUtility.convertToCriteriaPath(parent, p.getPath());
// If source and target of an association use the same name for their key we get conflicts with the alias.
// Therefore it is necessary to unify them.
selection.alias(association.getAlias() + ALIAS_SEPARATOR + p.getAlias());
selections.add(selection);
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
private boolean pathContainsCollection(final JPAPath p) {
for (final JPAElement pathElement : p.getPath()) {
if (pathElement instanceof final JPAAttribute attribute && attribute.isCollection()) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandLevelWrapper.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAExpandLevelWrapper.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.ApplyOption;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption;
import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.FormatOption;
import org.apache.olingo.server.api.uri.queryoption.IdOption;
import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataExpandPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataSkipTokenProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.uri.JPASkipOptionImpl;
import com.sap.olingo.jpa.processor.core.uri.JPATopOptionImpl;
import com.sap.olingo.jpa.processor.core.uri.JPAUriResourceNavigationImpl;
// TODO In case of second level $expand expandItem.getResourcePath() returns an empty UriInfoResource => Bug or
// Feature?
final class JPAExpandLevelWrapper implements JPAExpandItem, JPAExpandItemPageable {
private final ExpandOption option;
private final ExpandItem item;
private final JPAEntityType jpaEntityType;
private final LevelsExpandOption levelOptions;
private final EdmNavigationProperty navigationPath;
private Optional<JPAODataExpandPage> page;
JPAExpandLevelWrapper(final JPAServiceDocument sd, final ExpandOption option, final ExpandItem item)
throws ODataApplicationException {
super();
this.option = option;
this.item = item;
this.levelOptions = determineLevel();
this.navigationPath = null;
this.page = Optional.empty();
try {
this.jpaEntityType = sd.getEntity(Utility.determineTargetEntityType(getUriResourceParts()));
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ENTITY_UNKNOWN,
HttpStatusCode.BAD_REQUEST, e, Utility.determineTargetEntityType(getUriResourceParts()).getName());
}
}
/**
* Special constructor to handle ..?$expand=*($levels=2) requests. This request come with a problem. They do not have
* a resource list within the expand item. This needs to be build up from the path.
* @param option
* @param jpaEntityType
* @param edmNavigationProperty
*/
JPAExpandLevelWrapper(final ExpandOption option, final JPAEntityType jpaEntityType,
final EdmNavigationProperty edmNavigationProperty, final ExpandItem item) {
this.option = option;
this.item = item;
this.levelOptions = determineLevel();
this.jpaEntityType = jpaEntityType;
this.navigationPath = edmNavigationProperty;
this.page = Optional.empty();
}
@Override
public List<CustomQueryOption> getCustomQueryOptions() {
return Collections.emptyList();
}
@Override
public ExpandOption getExpandOption() {
if (levelOptions.getValue() > 1 || levelOptions.isMax())
return new ExpandOptionWrapper(option, this, item);
else if ((levelOptions.getValue() == 1
&& item.getExpandOption() != null
&& !item.getExpandOption().getExpandItems().isEmpty()))
return new ExpandOptionWrapper(option, this, item);
else
return null;
}
@Override
public FilterOption getFilterOption() {
return item.getFilterOption();
}
@Override
public FormatOption getFormatOption() {
return null;
}
@Override
public IdOption getIdOption() {
return null;
}
@Override
public CountOption getCountOption() {
return item.getCountOption();
}
@Override
public OrderByOption getOrderByOption() {
return item.getOrderByOption();
}
@Override
public SearchOption getSearchOption() {
return item.getSearchOption();
}
@Override
public SelectOption getSelectOption() {
return item.getSelectOption();
}
@Override
public SkipOption getSkipOption() {
if (page.isPresent())
return new JPASkipOptionImpl(page.get().skip());
return item.getSkipOption();
}
@Override
public SkipTokenOption getSkipTokenOption() {
return null;
}
@Override
public TopOption getTopOption() {
if (page.isPresent())
return new JPATopOptionImpl(page.get().top());
return item.getTopOption();
}
@Override
public List<UriResource> getUriResourceParts() {
return item.getResourcePath() != null ? item.getResourcePath().getUriResourceParts() : buildResourceList();
}
@Override
public String getValueForAlias(final String alias) {
return null;
}
@Override
public JPAEntityType getEntityType() {
return jpaEntityType;
}
@Override
public ApplyOption getApplyOption() {
return null;
}
@Override
public DeltaTokenOption getDeltaTokenOption() {
return null;
}
@Override
public Optional<JPAODataSkipTokenProvider> getSkipTokenProvider() {
if (page.isPresent())
return Optional.ofNullable(page.get().skipToken());
return Optional.empty();
}
@Override
public void setPage(final JPAODataExpandPage page) {
this.page = Optional.ofNullable(page);
}
private LevelsExpandOption determineLevel() {
return item.getLevelsOption();
}
private List<UriResource> buildResourceList() {
if (navigationPath != null)
return Collections.singletonList(new JPAUriResourceNavigationImpl(navigationPath));
return Collections.emptyList();
}
private class ExpandOptionWrapper implements ExpandOption {
private final List<ExpandItem> items;
private final ExpandOption parentOptions;
private ExpandOptionWrapper(final ExpandOption expandOption, final UriInfoResource parentUriInfoResource,
final ExpandItem item) {
this.items = new ArrayList<>();
if (item.getLevelsOption().getValue() > 1 || item.getLevelsOption().isMax())
this.items.add(new ExpandLevelItemWrapper(item, parentUriInfoResource));
if (item.getExpandOption() != null)
this.items.addAll(buildAdditionalExpandItems(item));
this.parentOptions = expandOption;
}
private List<? extends ExpandItem> buildAdditionalExpandItems(final ExpandItem item) {
return item.getExpandOption().getExpandItems().stream()
.filter(i -> i.getLevelsOption() == null)
.toList();
}
@Override
public SystemQueryOptionKind getKind() {
return parentOptions.getKind();
}
@Override
public String getName() {
return parentOptions.getName();
}
@Override
public String getText() {
return parentOptions.getText();
}
@Override
public List<ExpandItem> getExpandItems() {
return items;
}
}
private class ExpandLevelItemWrapper implements ExpandItem {
private final ExpandItem parentItem;
private ExpandOption expandOption;
private final LevelsExpandOption levelOption;
private final UriInfoResource parentUriInfoResource;
private ExpandLevelItemWrapper(final ExpandItem parentItem, final UriInfoResource parentUriInfoResource) {
this.parentItem = parentItem;
this.levelOption = new LevelsExpandOptionWrapper(parentItem.getLevelsOption().isMax(),
parentItem.getLevelsOption().getValue());
this.parentUriInfoResource = parentUriInfoResource;
}
@Override
public LevelsExpandOption getLevelsOption() {
return levelOption;
}
@Override
public FilterOption getFilterOption() {
return parentItem.getFilterOption();
}
@Override
public SearchOption getSearchOption() {
return null;
}
@Override
public OrderByOption getOrderByOption() {
return parentItem.getOrderByOption();
}
@Override
public SkipOption getSkipOption() {
return parentItem.getSkipOption();
}
@Override
public TopOption getTopOption() {
return parentItem.getTopOption();
}
@Override
public CountOption getCountOption() {
return parentItem.getCountOption();
}
@Override
public SelectOption getSelectOption() {
return parentItem.getSelectOption();
}
@Override
public ExpandOption getExpandOption() {
if (expandOption == null)
expandOption = new ExpandOptionWrapper(parentItem.getExpandOption(), parentUriInfoResource, parentItem);
return expandOption;
}
@Override
public UriInfoResource getResourcePath() {
return parentItem.getResourcePath() != null ? parentItem.getResourcePath() : parentUriInfoResource;
}
@Override
public boolean isStar() {
return false;
}
@Override
public boolean isRef() {
return false;
}
@Override
public boolean hasCountPath() {
return false;
}
@Override
public EdmType getStartTypeFilter() {
return parentItem.getStartTypeFilter();
}
@Override
public ApplyOption getApplyOption() {
return null;
}
}
private static class LevelsExpandOptionWrapper implements LevelsExpandOption {
private final boolean isMax;
private final int level;
private LevelsExpandOptionWrapper(final boolean isMax, final int parentLevel) {
super();
this.isMax = isMax;
if (parentLevel != 0)
this.level = parentLevel - 1;
else
this.level = 0;
}
@Override
public boolean isMax() {
return isMax;
}
@Override
public int getValue() {
return level;
}
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/SelectionPathInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/SelectionPathInfo.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Immutable triple of sets, that are related to each other.
*
* @author Oliver Grande
* Created: 27.03.2020
*
* @param <T>
*/
class SelectionPathInfo<T> {
private final Set<T> odataSelections;
private final Set<T> requiredSelections;
private final Set<T> transientSelections;
private Set<T> joinedPersistent;
private Set<T> joinedRequested;
SelectionPathInfo(@Nullable final Set<T> odataSelections, @Nullable final Set<T> requitedSelections,
@Nullable final Set<T> transientSelections) {
super();
this.odataSelections = odataSelections == null ? Collections.emptySet() : odataSelections;
this.requiredSelections = requitedSelections == null ? Collections.emptySet() : requitedSelections;
this.transientSelections = transientSelections == null ? Collections.emptySet() : transientSelections;
}
SelectionPathInfo(@Nonnull final List<T> additionalODataSelections,
@Nonnull final SelectionPathInfo<T> jpaSelectionPath) {
this.odataSelections = new HashSet<>(additionalODataSelections);
this.odataSelections.addAll(jpaSelectionPath.odataSelections);
this.requiredSelections = jpaSelectionPath.requiredSelections;
this.transientSelections = jpaSelectionPath.transientSelections;
}
SelectionPathInfo() {
this.odataSelections = new HashSet<>();
this.requiredSelections = new HashSet<>();
this.transientSelections = new HashSet<>();
}
Set<T> getODataSelections() {
return odataSelections;
}
Set<T> getRequiredSelections() {
return requiredSelections;
}
Set<T> getTransientSelections() {
return transientSelections;
}
Set<T> joined() {
final Set<T> joined = new HashSet<>(odataSelections);
joined.addAll(requiredSelections);
joined.addAll(transientSelections);
return joined;
}
Set<T> joinedPersistent() {
if (joinedPersistent == null) {
joinedPersistent = new HashSet<>(odataSelections);
joinedPersistent.addAll(requiredSelections);
}
return joinedPersistent;
}
Set<T> joinedRequested() {
if (joinedRequested == null) {
joinedRequested = new HashSet<>(odataSelections);
joinedRequested.addAll(transientSelections);
}
return joinedRequested;
}
@Override
public String toString() {
return "SelectionPathInfo [odata=" + odataSelections + ", required=" + requiredSelections + ", transient="
+ transientSelections
+ "]";
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPARowNumberFilterQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPARowNumberFilterQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NO_JOIN_TABLE_TYPE;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toSet;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterComplier;
/**
*
* Generates a query containing row_number selections like:
*
* <pre>
* {@code
* SELECT
* ...
* row_number() over(
* partition by E1."CodePublisher", E1."ParentCodeID",E1."ParentDivisionCode"
* order by E1."CodePublisher" asc, E1."CodeID" asc, E1."DivisionCode" asc) rowNumber
* }
* </pre>
*
* Example requests:
* <ul>
* <li>{@code
* AdministrativeDivisions?$filter=CodeID eq
* 'NUTS1'&$top=4&$skip=1&$expand=Children($top=2;$expand=Children($top=1;$skip=1))
* }</li>
* <li>{@code
* AdministrativeDivisions?$filter=CodeID eq
* 'NUTS1'&$top=4&$skip=1&$expand=Children($top=2;$expand=Parent($top=1;$skip=1))
* }</li>
* <li>{@code
* Organizations?$top=1&$select=Name1&$expand=SupportEngineers($select=FirstName,LastName;$top=1;$expand=SupportedOrganizations($top=1))
* }</li>
* </ul>
* <p>
* To filter on the provided row number a wrapping query is required.
* Such a queries are only triggered if <i>odata-jpa-processor-cb</i> is used.
* <p>
* Integration test: {@link com.sap.olingo.jpa.processor.core.query.TestJPAProcessorExpand}
* <p>
* @author Oliver Grande
*/
final class JPARowNumberFilterQuery extends JPAExpandFilterQuery {
private final JPAFilterComplier filter;
private final Set<JPAPath> outerSelections;
private final boolean useInverse;
JPARowNumberFilterQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPANavigationPropertyInfo navigationInfo, final JPAAbstractQuery parent,
final Optional<JPAAssociationPath> childAssociation) throws ODataException {
super(odata, requestContext, new JPANavigationPropertyInfo(navigationInfo), parent, childAssociation
.orElse(null));
this.outerSelections = navigationInfo.getAssociationPath().getLeftColumnsList().stream().collect(toSet());
this.useInverse = false;
filter = lastInfo.getFilterCompiler();
filter.compile();
}
JPARowNumberFilterQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPANavigationPropertyInfo navigationInfo, final JPAAbstractQuery parent, final JPAAssociationPath association,
final JPAAssociationPath childAssociation, final SelectionPathInfo<JPAPath> selectionPath) throws ODataException {
super(odata, requestContext, new JPANavigationPropertyInfo(navigationInfo), parent, association,
childAssociation);
this.outerSelections = selectionPath.joinedPersistent();
this.useInverse = true;
filter = lastInfo.getFilterCompiler();
filter.compile();
}
/**
*
*/
@SuppressWarnings("unchecked")
@Nonnull
@Override
public <T> Subquery<T> getSubQuery(@Nullable final Subquery<?> childQuery,
@Nullable final VisitableExpression expression, final List<Path<Comparable<?>>> inPath)
throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createSubQuery")) {
final ProcessorSubquery<T> nextQuery = (ProcessorSubquery<T>) this.subQuery;
this.queryRoot = subQuery.from(this.jpaEntity.getTypeClass());
buildJoinTable(emptyList(), outerSelections, null);
final List<Selection<?>> selections = createSelectForParent();
selections.addAll(crateSelectionJoinTable());
selections.add(createRowNumber(useInverse));
nextQuery.where(createWhereSubQuery(childQuery, useInverse));
nextQuery.multiselect(selections);
return nextQuery;
}
}
private List<? extends Selection<?>> crateSelectionJoinTable() throws ODataJPAQueryException {
if (queryJoinTable != null) {
try {
final List<JPAOnConditionItem> columns = association.getJoinTable().getJoinColumns();
debugger.trace(this, "Creating SELECT snipped for join table %s with join conditions %s", queryJoinTable
.toString(), columns);
return columns
.stream()
.map(key -> mapOnToSelection(key.getRightPath(), queryJoinTable, null))
.toList();
} catch (final ODataJPAModelException e) {
if (e.getId().equals(NO_JOIN_TABLE_TYPE.getKey())) {
throw new ODataJPAQueryException(QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING, INTERNAL_SERVER_ERROR,
association.getJoinTable().getTableName());
}
throw new ODataJPAQueryException(QUERY_PREPARATION_ERROR, INTERNAL_SERVER_ERROR, e);
}
}
return emptyList();
}
private List<Selection<?>> createSelectForParent() {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createSelectClause")) {
final List<Selection<?>> selections = new ArrayList<>();
// Build select clause
for (final JPAPath jpaPath : this.outerSelections) {
if (jpaPath.isPartOfGroups(groups)) {
final Path<?> path = ExpressionUtility.convertToCriteriaPath(joinTables, queryRoot, jpaPath);
path.alias(jpaPath.getAlias());
selections.add(path);
}
}
return selections;
}
}
private Expression<Long> createRowNumber(final boolean inverse) throws ODataApplicationException {
try {
@SuppressWarnings("unchecked")
final List<Path<Comparable<?>>> pathList = (List<Path<Comparable<?>>>) createWhereKeyInPathList(
inverse ? association : childAssociation
.orElseThrow(() -> new ODataJPAQueryException(QUERY_PREPARATION_ERROR, INTERNAL_SERVER_ERROR)),
queryJoinTable == null ? queryRoot : queryJoinTable);
final List<Order> orderBy = createOrderBy();
return (Expression<Long>) ((ProcessorCriteriaBuilder) cb).rowNumber()
.orderBy(orderBy.isEmpty() ? singletonList(cb.asc(queryRoot)) : orderBy)
.partitionBy(pathList)
.alias(ROW_NUMBER_COLUMN_NAME);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
@Override
protected Expression<Boolean> applyAdditionalFilter(final Expression<Boolean> where)
throws ODataApplicationException {
if (filter != null && aggregationType == null)
try {
return addWhereClause(where, filter.compile());
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return where;
}
private List<Order> createOrderBy() throws ODataApplicationException {
final JPAOrderByBuilder orderBy = new JPAOrderByBuilder(jpaEntity, queryRoot, cb, groups);
final var orderByAttributes = getOrderByAttributes(lastInfo.getUriInfo().getOrderByOption()).stream()
.map(attribute -> attribute.setTarget(queryRoot, joinTables, cb))
.collect(Collectors.toList()); // NOSONAR get mutable list
return orderBy.createOrderByList(emptyMap(), orderByAttributes);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationSubQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationSubQuery.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.filter.JPAFilterElementComplier;
import com.sap.olingo.jpa.processor.core.filter.JPAOperationConverter;
public abstract class JPANavigationSubQuery extends JPAAbstractSubQuery {
protected final List<UriParameter> keyPredicates;
JPANavigationSubQuery(final OData odata, final JPAServiceDocument sd, final JPAEntityType jpaEntity,
final EntityManager em, final JPAAbstractQuery parent, final From<?, ?> from,
final JPAAssociationPath association, final Optional<JPAODataClaimProvider> claimsProvider,
final List<UriParameter> keyPredicates) throws ODataApplicationException {
super(odata, sd, jpaEntity, em, parent, from, association, claimsProvider);
this.keyPredicates = keyPredicates;
this.subQuery = createSubQuery(parent);
this.locale = parent.getLocale();
createRoots(association);
}
Subquery<?> createSubQuery(final JPAAbstractQuery parent) {
// Null if there is no et for collection property
if (this.jpaEntity == null)
return parent.getQuery().subquery(((JPAEntityType) association.getSourceType()).getKeyType());
else
return parent.getQuery().subquery(this.jpaEntity.getKeyType());
}
final void buildExpression(final VisitableExpression expression, final List<String> groups)
throws ODataApplicationException {
this.filterComplier = new JPAFilterElementComplier(odata, sd, em, jpaEntity, new JPAOperationConverter(cb,
getContext().getOperationConverter(), getContext().getQueryDirectives()), null, this, expression, association,
groups);
createDescriptionJoin();
}
void createDescriptionJoin() throws ODataApplicationException {
final HashMap<String, From<?, ?>> joinTables = new HashMap<>();
generateDescriptionJoin(joinTables, determineAllDescriptionPath(), getRoot());
}
private Set<JPAPath> determineAllDescriptionPath() throws ODataApplicationException {
final Set<JPAPath> allPath = new HashSet<>();
if (filterComplier != null) {
for (final JPAPath path : filterComplier.getMember()) {
if (path.getLeaf() instanceof JPADescriptionAttribute)
allPath.add(path);
}
}
return allPath;
}
protected void createGroupBy(final Subquery<?> subQuery, final From<?, ?> from,
final List<JPAOnConditionItem> conditionItems) {
final List<Expression<?>> groupByList = new ArrayList<>();
for (final JPAOnConditionItem onCondition : conditionItems) {
final var subPath = ExpressionUtility.convertToCriteriaPath(from, onCondition.getRightPath().getPath());
groupByList.add(subPath);
}
subQuery.groupBy(groupByList);
}
protected List<JPAOnConditionItem> determineJoinColumns() throws ODataJPAQueryException {
try {
final List<JPAOnConditionItem> conditionItems = association.getJoinColumnsList();
if (conditionItems.isEmpty())
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_JOIN_NOT_DEFINED,
HttpStatusCode.INTERNAL_SERVER_ERROR, association.getTargetType().getExternalName(), association
.getSourceType().getExternalName());
return conditionItems;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_RESULT_NAVI_PROPERTY_UNKNOWN,
HttpStatusCode.INTERNAL_SERVER_ERROR, e, association.getAlias());
}
}
@SuppressWarnings("unchecked")
@Override
public From<?, ?> getRoot() {
assert queryRoot != null;
return queryRoot;
}
@Override
public List<Path<Comparable<?>>> getLeftPaths() throws ODataJPAIllegalAccessException {
return Collections.emptyList();
}
@Override
protected Expression<Boolean> createWhereEnhancement(final JPAEntityType et, final From<?, ?> from)
throws ODataJPAProcessorException {
return null;
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAKeyPair.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAKeyPair.java | package com.sap.olingo.jpa.processor.core.query;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jakarta.persistence.AttributeConverter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.UuidSortOrder;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAKeyPairException;
/**
* A pair of comparable entity keys.<br>
* Such a pair is used to forward the lowest and highest key value from a query to the dependent $expand query in case
* the original query was restricted by <code>$top</code> and/or <code>$skip</code>.
* The pair is seen as closed interval, that is min and max are seen as part of the result. In case an attribute of the
* key has a conversion, the converted value is used for the comparison.
*
* @author Oliver Grande
* Created: 13.10.2019
* @since 0.3.6
* @param <T>
*/
@SuppressWarnings("rawtypes")
public class JPAKeyPair {
private Map<JPAAttribute, Comparable> min;
private Map<JPAAttribute, Comparable> max;
private final List<JPAAttribute> keyDefinition;
private final UuidSortOrder uuidSortOrder;
public JPAKeyPair(final List<JPAAttribute> keyDef, final JPAODataQueryDirectives queryDirectives) {
super();
this.keyDefinition = keyDef;
this.uuidSortOrder = queryDirectives.getUuidSortOrder();
}
public Map<JPAAttribute, Comparable> getMin() {
return min;
}
@SuppressWarnings("unchecked")
public <Y extends Comparable<? super Y>> Y getMinElement(final JPAAttribute keyElement) {
return (Y) min.get(keyElement);
}
public Map<JPAAttribute, Comparable> getMax() {
return max;
}
@SuppressWarnings("unchecked")
public <Y extends Comparable<? super Y>> Y getMaxElement(final JPAAttribute keyElement) {
return (Y) max.get(keyElement);
}
public boolean hasUpperBoundary() {
return max != null && !min.equals(max);
}
public void setValue(final Map<JPAAttribute, Comparable> keyValues) throws ODataJPAKeyPairException {
for (final JPAAttribute keyElement : keyDefinition) {
final Comparable value = keyValues.get(keyElement);
if (min == null || min.get(keyElement) == null
|| (value != null
&& compareValues(value, min, keyElement) < 0)) {
if (max == null)
max = min;
min = keyValues;
return;
} else if (max == null || compareValues(value, max, keyElement) > 0) {
max = keyValues;
return;
} else if (compareValues(value, max, keyElement) != 0) {
return;
}
}
}
@SuppressWarnings("unchecked")
private int compareValues(final Comparable value, final Map<JPAAttribute, Comparable> comp,
final JPAAttribute keyElement) throws ODataJPAKeyPairException {
final Comparable minValue = comp.get(keyElement);
if (keyElement.getRawConverter() != null) {
final Class<?> dbType = keyElement.getDbType();
try {
final AttributeConverter<Object, Object> converter = keyElement.getRawConverter();
if (dbType != null
&& (keyElement.getDbType() == Byte[].class
|| keyElement.getDbType() == byte[].class)) {
return new ComparableByteArray(
ComparableByteArray.unboxedArray(converter.convertToDatabaseColumn(value))).compareTo(
ComparableByteArray.unboxedArray(converter.convertToDatabaseColumn(minValue)));
}
return ((Comparable) converter.convertToDatabaseColumn(value))
.compareTo(converter.convertToDatabaseColumn(minValue));
} catch (final ClassCastException e) {
throw new ODataJPAKeyPairException(e, dbType == null ? keyElement.getType().getSimpleName()
: dbType.getSimpleName());
}
} else if (minValue instanceof final UUID uuid && uuidSortOrder != null) {
return switch (uuidSortOrder) {
case AS_STRING -> value.toString().compareTo(uuid.toString());
case AS_BYTE_ARRAY -> new ComparableByteArray(convertUUIDToBytes((UUID) value))
.compareTo(convertUUIDToBytes(uuid));
case AS_JAVA_UUID -> value.compareTo(uuid);
};
}
return value.compareTo(minValue);
}
@Override
public String toString() {
return "JPAKeyPair [min=" + min + ", max=" + max + ", hasUpperBoundary=" + hasUpperBoundary() + "]";
}
private byte[] convertUUIDToBytes(final UUID uuid) {
final ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationPropertyInfoAccess.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPANavigationPropertyInfoAccess.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.List;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
public interface JPANavigationPropertyInfoAccess {
JPAAssociationPath getAssociationPath();
UriResourcePartTyped getUriResource();
List<UriParameter> getKeyPredicates();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACountWatchDog.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPACountWatchDog.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.COUNT_NON_SUPPORTED_COUNT;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.helper.AbstractWatchDog;
/**
*
* @author Oliver Grande
* @since 1.1.1
* 12.04.2023
*/
class JPACountWatchDog extends AbstractWatchDog {
static final String TERM = "CountRestrictions";
static final String VOCABULARY_ALIAS = "Capabilities";
static final String COUNTABLE = "Countable";
static final String NON_COUNTABLE_PROPERTIES = "NonCountableProperties";
static final String NON_COUNTABLE_NAVIGATION_PROPERTIES = "NonCountableNavigationProperties";
private final String externalName;
private final Optional<CsdlAnnotation> annotation;
private final boolean isCountable;
private final List<String> nonCountableProperties;
private final List<String> nonCountableNavigationProperties;
JPACountWatchDog(final Optional<JPAAnnotatable> annotatable) throws ODataJPAQueryException {
Map<String, CsdlExpression> properties = Collections.emptyMap();
if (annotatable.isPresent()) {
try {
externalName = annotatable.get().getExternalName();
annotation = Optional.ofNullable(annotatable.get().getAnnotation(VOCABULARY_ALIAS, TERM));
if (annotation.isPresent())
properties = getAnnotationProperties(annotation);
else
properties = Collections.emptyMap();
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
} else {
annotation = Optional.empty();
externalName = "";
}
this.isCountable = determineCountable(properties);
this.nonCountableProperties = determineNonCountableProperties(properties);
this.nonCountableNavigationProperties = determineNonCountableNavigationProperties(properties);
}
/**
* Example requests:
* - /AnnotationsParents?$count=true
* - /AnnotationsParents/$count
* - /AdministrativeDivisions(CodePublisher='Eurostat',CodeID='NUTS2',DivisionCode='BE24')/Children/$count
* - /AdministrativeDivisions(CodePublisher='Eurostat',CodeID='NUTS2',DivisionCode='BE24')/Children?$count=true
* - /Organizations('1')/Comment/$count
* - /Organizations('1')/Comment?$count=true
* - /Collections('501')/Nested/$count
* @param uriResource
* @throws ODataJPAQueryException
* @throws ODataJPAProcessorException
*/
void watch(final UriInfoResource uriResource) throws ODataJPAProcessorException {
final boolean count = determineCount(uriResource);
if (count) {
if (!isCountable)
throw new ODataJPAProcessorException(COUNT_NON_SUPPORTED_COUNT, HttpStatusCode.BAD_REQUEST, externalName);
if (!propertyIsCountable(uriResource))
throw new ODataJPAProcessorException(COUNT_NON_SUPPORTED_COUNT, HttpStatusCode.BAD_REQUEST, externalName);
if (!navigationIsCountable(uriResource))
throw new ODataJPAProcessorException(COUNT_NON_SUPPORTED_COUNT, HttpStatusCode.BAD_REQUEST, externalName);
}
}
private boolean navigationIsCountable(final UriInfoResource uriResource) {
return !nonCountableNavigationProperties.contains(buildPath(uriResource));
}
private boolean propertyIsCountable(final UriInfoResource uriResource) {
return !nonCountableProperties.contains(buildPath(uriResource));
}
private String buildPath(final UriInfoResource uriResource) {
final List<String> pathItems = new ArrayList<>(uriResource.getUriResourceParts().size());
for (int i = 1; i < uriResource.getUriResourceParts().size() - 1; i++) {
final UriResource resourcePart = uriResource.getUriResourceParts().get(i);
if (resourcePart instanceof final UriResourceNavigation navigation)
pathItems.add(navigation.getProperty().getName());
if (resourcePart instanceof final UriResourceProperty property && property.isCollection())
pathItems.add(property.getProperty().getName());
}
return pathItems.stream().collect(Collectors.joining("/"));
}
private boolean determineCount(final UriInfoResource uriResource) {
final List<UriResource> uriResourceParts = uriResource.getUriResourceParts();
if (uriResourceParts != null
&& !uriResourceParts.isEmpty()
&& uriResourceParts.get(uriResourceParts.size() - 1).getKind() == UriResourceKind.count)
return true;
return Optional.ofNullable(uriResource.getCountOption())
.map(CountOption::getValue)
.orElse(false);
}
String getExternalName() {
return externalName;
}
boolean isCountable() {
return isCountable;
}
List<String> getNonCountableProperties() {
return nonCountableProperties;
}
List<String> getNonCountableNavigationProperties() {
return nonCountableNavigationProperties;
}
private boolean determineCountable(final Map<String, CsdlExpression> properties) {
return determineConstantExpression(properties, COUNTABLE)
.map(Boolean::valueOf)
.orElse(true);
}
private List<String> determineNonCountableProperties(final Map<String, CsdlExpression> properties) {
return getNavigationPathItems(properties, NON_COUNTABLE_PROPERTIES);
}
private List<String> determineNonCountableNavigationProperties(final Map<String, CsdlExpression> properties) {
return getNavigationPathItems(properties, NON_COUNTABLE_NAVIGATION_PROPERTIES);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractExpandSubQuery.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/JPAAbstractExpandSubQuery.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING;
import static java.util.Collections.singletonList;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJoinTable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.properties.JPAProcessorAttribute;
abstract class JPAAbstractExpandSubQuery extends JPAAbstractExpandQuery {
JPAAbstractExpandSubQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAInlineItemInfo item) throws ODataException {
super(odata, requestContext, item);
((ProcessorCriteriaBuilder) cb).resetParameterBuffer();
}
JPAAbstractExpandSubQuery(final OData odata, final JPAODataRequestContextAccess requestContext,
final JPAEntityType et, final JPAAssociationPath association, final List<JPANavigationPropertyInfo> hops)
throws ODataException {
super(odata, requestContext, et, association, hops);
}
@Override
protected Map<String, From<?, ?>> createFromClause(final List<JPAProcessorAttribute> orderByTarget,
final Collection<JPAPath> selectionPath, final CriteriaQuery<?> query, final JPANavigationPropertyInfo lastInfo)
throws ODataApplicationException, JPANoSelectionException {
final Map<String, From<?, ?>> joinTables = new HashMap<>();
debugger.trace(this, "Create FROM clause for %s", query.toString());
createFromClauseRoot(query, joinTables, lastInfo);
target = root;
createFromClauseJoinTable(joinTables, query);
lastInfo.setFromClause(target);
createFromClauseDescriptionFields(selectionPath, joinTables, target, singletonList(lastInfo));
return joinTables;
}
LinkedList<JPAAbstractQuery> buildSubQueries(final JPAAbstractQuery query) throws ODataException {
final LinkedList<JPAAbstractQuery> hops = new LinkedList<>();
hops.push(query);
for (int i = navigationInfo.size() - 2; i >= 0; i--) {
final JPANavigationPropertyInfo hop = navigationInfo.get(i);
if (hop.getUriInfo() != null) {
final var associationIndex = determineAssociationPathIndex(navigationInfo, i);
final JPAAbstractQuery parent = hops.getLast();
final JPAAssociationPath childAssociation = associationIndex >= 0
? navigationInfo.get(associationIndex).getAssociationPath()
: null;
hops.push(new JPAExpandFilterQuery(odata, requestContext, hop, parent, childAssociation));
debugger.trace(this, "Sub query created: %s for %s", hops.getFirst().getQuery(), hops.getFirst().jpaEntity);
}
}
return hops;
}
Subquery<Object> linkSubQueries(final LinkedList<JPAAbstractQuery> hops) throws ODataApplicationException {
Subquery<Object> subQuery = null;
while (!hops.isEmpty() && hops.getFirst() instanceof JPAAbstractSubQuery) {
final JPAAbstractSubQuery hop = (JPAAbstractSubQuery) hops.pop();
subQuery = hop.getSubQuery(subQuery, null, Collections.emptyList());
}
return subQuery;
}
void createFromClauseJoinTable(final Map<String, From<?, ?>> joinTables, final CriteriaQuery<?> query)
throws ODataJPAQueryException {
if (association.hasJoinTable()) {
final JPAJoinTable joinTable = association.getJoinTable();
final JPAEntityType joinTableEt = Optional.ofNullable(joinTable.getEntityType())
.orElseThrow(() -> new ODataJPAQueryException(QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING,
INTERNAL_SERVER_ERROR, joinTable.getTableName()));
debugger.trace(this, "Join table found: %s, join will be created", joinTableEt.toString());
root = query.from(joinTableEt.getTypeClass());
root.alias(association.getAlias());
joinTables.put(association.getAlias(), root);
}
}
List<Selection<?>> addSelectJoinTable(final List<Selection<?>> selections) throws ODataJPAQueryException {
if (association.hasJoinTable()) {
try {
final List<Selection<?>> additionalSelections = new ArrayList<>(selections);
final JPAJoinTable joinTable = association.getJoinTable();
debugger.trace(this, "Creating SELECT snipped for join table %s with join conditions %s", joinTable.toString(),
joinTable.getJoinColumns());
for (final JPAOnConditionItem jc : association.getJoinTable().getJoinColumns()) {
final Path<?> path = root.get(jc.getRightPath().getLeaf().getInternalName());
path.alias(association.getAlias() + ALIAS_SEPARATOR + jc.getLeftPath().getAlias());
additionalSelections.add(path);
}
return additionalSelections;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
return selections;
}
Expression<Boolean> createExpandWhere(final JPANavigationPropertyInfo navigationInfo)
throws ODataApplicationException {
try {
return navigationInfo.getFilterCompiler().compile();
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(QUERY_PREPARATION_FILTER_ERROR, HttpStatusCode.BAD_REQUEST, e);
}
}
Expression<Boolean> createWhere(final Subquery<?> subQuery, final JPANavigationPropertyInfo navigationInfo)
throws ODataApplicationException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "createWhere")) {
jakarta.persistence.criteria.Expression<Boolean> whereCondition = null;
// Given keys: Organizations('1')/Roles(...)
whereCondition = createWhereByKey(navigationInfo);
whereCondition = addWhereClause(whereCondition, createWhereTableJoin(root, target, association, true));
whereCondition = addWhereClause(whereCondition, createWhereKeyIn(this.association, root, subQuery));
whereCondition = addWhereClause(whereCondition, createExpandWhere(navigationInfo));
whereCondition = addWhereClause(whereCondition, createWhereEnhancement());
whereCondition = addWhereClause(whereCondition, createProtectionWhereForEntityType(claimsProvider, jpaEntity,
target));
return whereCondition;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
private void createFromClauseRoot(final CriteriaQuery<?> query, final Map<String, From<?, ?>> joinTables,
final JPANavigationPropertyInfo lastInfo) throws ODataJPAQueryException {
try {
final JPAEntityType sourceEt = lastInfo.getEntityType();
this.root = query.from(sourceEt.getTypeClass());
joinTables.put(sourceEt.getExternalFQN().getFullQualifiedNameAsString(), root);
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, INTERNAL_SERVER_ERROR);
}
}
private int determineAssociationPathIndex(final List<JPANavigationPropertyInfo> navigationInfo, final int index) {
// look ahead
var readIndex = index - 1;
while (readIndex >= 0
&& navigationInfo.get(readIndex).getUriInfo() == null)
readIndex--;
return readIndex;
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.