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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/exceptions/NotImplementedException.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/exceptions/NotImplementedException.java | package com.sap.olingo.jpa.processor.cb.exceptions;
public class NotImplementedException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -5704193843480029363L;
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/StringBuilderJoiner.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/StringBuilderJoiner.java | package com.sap.olingo.jpa.processor.cb.joiner;
import java.util.Objects;
import javax.annotation.Nonnull;
final class StringBuilderJoiner<T> {
private static final String EMPTY_RESULT = "";
private final StringBuilder statement;
private final String delimiter;
private final int initLength;
StringBuilderJoiner(@Nonnull final StringBuilder statement, @Nonnull final String delimiter) {
this.statement = Objects.requireNonNull(statement);
this.delimiter = Objects.requireNonNull(delimiter);
this.initLength = statement.length();
}
public StringBuilderJoiner<T> add(final T newElement) {
((SqlConvertible) newElement).asSQL(prepareStatement());
return this;
}
public StringBuilderJoiner<T> merge() {
return this;
}
public String finish() {
return EMPTY_RESULT;
}
private StringBuilder prepareStatement() {
if (statement.length() != initLength) {
statement.append(delimiter);
}
return statement;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/ExpressionCollector.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/ExpressionCollector.java | package com.sap.olingo.jpa.processor.cb.joiner;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Predicate.BooleanOperator;
public class ExpressionCollector implements Collector<Expression<Boolean>, ExpressionJoiner, Expression<Boolean>> {
final Supplier<ExpressionJoiner> supplier;
public ExpressionCollector(@Nonnull final CriteriaBuilder cb, @Nonnull final BooleanOperator operator) {
this.supplier = () -> new ExpressionJoiner(cb, operator);
}
@Override
public Supplier<ExpressionJoiner> supplier() {
return supplier;
}
@Override
public BinaryOperator<ExpressionJoiner> combiner() {
return null;
}
@Override
public BiConsumer<ExpressionJoiner, Expression<Boolean>> accumulator() {
return ExpressionJoiner::add;
}
@Override
public Function<ExpressionJoiner, Expression<Boolean>> finisher() {
return ExpressionJoiner::finish;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/SetExpression.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/SetExpression.java | package com.sap.olingo.jpa.processor.cb.joiner;
public interface SetExpression extends SqlConvertible {
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/ExpressionJoiner.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/ExpressionJoiner.java | package com.sap.olingo.jpa.processor.cb.joiner;
import java.util.Objects;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Predicate.BooleanOperator;
final class ExpressionJoiner {
private final CriteriaBuilder cb;
private final BooleanOperator operator;
private boolean isFirst;
private Expression<Boolean> expression;
ExpressionJoiner(@Nonnull final CriteriaBuilder cb, @Nonnull final BooleanOperator operator) {
this.cb = Objects.requireNonNull(cb);
this.operator = Objects.requireNonNull(operator);
this.isFirst = true;
}
public ExpressionJoiner add(@Nonnull final Expression<Boolean> newExpression) {
if (isFirst) {
this.expression = newExpression;
isFirst = false;
} else if (operator == BooleanOperator.AND) {
this.expression = cb.and(expression, newExpression);
} else {
this.expression = cb.or(expression, newExpression);
}
return this;
}
public ExpressionJoiner merge() {
return this;
}
public Expression<Boolean> finish() {
return expression;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/StringBuilderCollector.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/StringBuilderCollector.java | package com.sap.olingo.jpa.processor.cb.joiner;
import java.util.Collections;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Selection;
public abstract class StringBuilderCollector<T> implements Collector<T, StringBuilderJoiner<T>, String> {
final Supplier<StringBuilderJoiner<T>> supplier;
StringBuilderCollector(@Nonnull final StringBuilder statement, @Nonnull final String delimiter) {
this.supplier = () -> new StringBuilderJoiner<>(statement, delimiter);
}
@Override
public Supplier<StringBuilderJoiner<T>> supplier() {
return supplier;
}
@Override
public BinaryOperator<StringBuilderJoiner<T>> combiner() {
return null;
}
@Override
public BiConsumer<StringBuilderJoiner<T>, T> accumulator() {
return StringBuilderJoiner::add;
}
@Override
public Function<StringBuilderJoiner<T>, String> finisher() {
return StringBuilderJoiner::finish;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
public static class OrderCollector extends StringBuilderCollector<Order> {
public OrderCollector(@Nonnull final StringBuilder statement, @Nonnull final String delimiter) {
super(statement, delimiter);
}
}
public static class ExpressionCollector extends StringBuilderCollector<Expression<?>> {
public ExpressionCollector(@Nonnull final StringBuilder statement, @Nonnull final String delimiter) {
super(statement, delimiter);
}
}
public static class SelectionCollector extends StringBuilderCollector<Selection<?>> {
public SelectionCollector(@Nonnull final StringBuilder statement, @Nonnull final String delimiter) {
super(statement, delimiter);
}
}
public static class SetCollector extends StringBuilderCollector<SetExpression> {
public SetCollector(@Nonnull final StringBuilder statement, @Nonnull final String delimiter) {
super(statement, delimiter);
}
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/SqlConvertible.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/joiner/SqlConvertible.java | package com.sap.olingo.jpa.processor.cb.joiner;
import javax.annotation.Nonnull;
public interface SqlConvertible {
public StringBuilder asSQL(@Nonnull final StringBuilder statement);
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlAggregation.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlAggregation.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlAggregation {
AVG("AVG"),
COUNT("COUNT"),
SUM("SUM"),
MAX("MAX"),
MIN("MIN");
private String keyWord;
private SqlAggregation(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/PathImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/PathImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.metamodel.Bindable;
import jakarta.persistence.metamodel.MapAttribute;
import jakarta.persistence.metamodel.PluralAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import org.apache.commons.logging.LogFactory;
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.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
/**
* Represents a simple or compound attribute path from a
* bound type or collection, and is a "primitive" expression.
*
* @param <X> the type referenced by the path
*
* @author Oliver Grande
* @since 0.3.8
*/
class PathImpl<X> extends ExpressionImpl<X> implements Path<X> {
final Optional<JPAPath> path;
final Optional<PathImpl<?>> parent;
final Optional<String> tableAlias;
JPAEntityType st;
PathImpl(@Nonnull final JPAPath path, @Nonnull final Optional<PathImpl<?>> parent, final JPAEntityType type,
final Optional<String> tableAlias) {
this(Optional.of(path), parent, type, tableAlias);
}
PathImpl(@Nonnull final Optional<JPAPath> path, @Nonnull final Optional<PathImpl<?>> parent, final JPAEntityType type,
@Nonnull final Optional<String> tableAlias) {
super();
this.path = Objects.requireNonNull(path);
this.parent = Objects.requireNonNull(parent);
this.st = type;
this.tableAlias = Optional.ofNullable(tableAliasFromParent(tableAlias));
if (st == null)
LogFactory.getLog(getClass()).info("Type not provided for " + path);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
tableAlias.ifPresent(alias -> {
statement.append(alias);
statement.append(DOT);
});
path.ifPresent(p -> statement.append(p.getDBFieldName()));
return statement;
}
/**
* Create a path corresponding to the referenced
* map-valued attribute.
* @param map map-valued attribute
* @return expression corresponding to the referenced attribute
*/
@Override
public <K, V, M extends Map<K, V>> Expression<M> get(final MapAttribute<X, K, V> map) {
throw new NotImplementedException();
}
/**
* Create a path corresponding to the referenced
* collection-valued attribute.
* @param collection collection-valued attribute
* @return expression corresponding to the referenced attribute
*/
@Override
public <E, C extends Collection<E>> Expression<C> get(final PluralAttribute<X, C, E> collection) {
throw new NotImplementedException();
}
/**
* Create a path corresponding to the referenced
* single-valued attribute.
* @param attribute single-valued attribute
* @return path corresponding to the referenced attribute
*/
@Override
public <Y> Path<Y> get(final SingularAttribute<? super X, Y> attribute) {
throw new NotImplementedException();
}
/**
* Create a path corresponding to the referenced attribute.
*
* <p>
* Note: Applications using the string-based API may need to
* specify the type resulting from the <code>get</code> operation in order
* to avoid the use of <code>Path</code> variables.
*
* <pre>
* For example:
*
* CriteriaQuery<Person> q = cb.createQuery(Person.class);
* Root<Person> p = q.from(Person.class);
* q.select(p)
* .where(cb.isMember("joe",
* p.<Set<String>>get("nicknames")));
*
* rather than:
*
* CriteriaQuery<Person> q = cb.createQuery(Person.class);
* Root<Person> p = q.from(Person.class);
* Path<Set<String>> nicknames = p.get("nicknames");
* q.select(p)
* .where(cb.isMember("joe", nicknames));
* </pre>
*
* @param attributeName name of the attribute
* @return path corresponding to the referenced attribute
* @throws IllegalStateException if invoked on a path that
* corresponds to a basic type
* @throws IllegalArgumentException if attribute of the given
* name does not otherwise exist
*/
@Override
public <Y> Path<Y> get(final String attributeName) {
try {
JPAStructuredType source;
if (this.path.isPresent()) {
if (this.path.get().getLeaf().isComplex()) {
source = this.path.get().getLeaf().getStructuredType();
} else {
throw new IllegalArgumentException("Parent not structured");
}
} else {
source = st;
}
final JPAAttribute attribute = source.getDeclaredAttribute(attributeName)
.orElseThrow(() -> new IllegalArgumentException("'" + attributeName + "' not found at " + st
.getInternalName()));
if (this.path.isPresent()) {
if (isKeyPath(path.get())) {
return createPathForKeyAttribute(attribute);
}
return createPathForDescriptionAttribute(attribute);
} else {
return createPathForAttribute(attribute);
}
} catch (final ODataJPAModelException e) {
throw new IllegalArgumentException("'" + attributeName + "' not found", e);
}
}
private <Y> Path<Y> createPathForDescriptionAttribute(final JPAAttribute attribute) throws ODataJPAModelException {
final StringBuilder pathDescription = new StringBuilder(path.get().getAlias()).append(JPAPath.PATH_SEPARATOR)
.append(attribute.getExternalName());
final var jpaPath = st.getPath(pathDescription.toString(), false);
if (jpaPath != null)
return new PathImpl<>(jpaPath, Optional.of(this), st, tableAlias);
else
throw new IllegalStateException();
}
private <Y> Path<Y> createPathForKeyAttribute(final JPAAttribute attribute) throws ODataJPAModelException {
final var jpaPath = st.getPath(attribute.getExternalName());
if (jpaPath != null)
return new PathImpl<>(jpaPath, Optional.of(this), st, tableAlias);
else
throw new IllegalStateException();
}
private <Y> Path<Y> createPathForAttribute(final JPAAttribute attribute) throws ODataJPAModelException {
final var jpaPath = st.getPath(attribute.getExternalName(), false);
if (jpaPath != null)
return new PathImpl<>(jpaPath, Optional.of(this), st, tableAlias);
else
throw new IllegalStateException();
}
boolean isKeyPath(final JPAPath jpaPath) {
try {
return st.getKeyPath()
.stream()
.anyMatch(keyPath -> keyPath.getAlias().equals(jpaPath.getAlias()));
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
/**
* Return the bindable object that corresponds to the
* path expression.
* @return bindable object corresponding to the path
*/
@Override
public Bindable<X> getModel() {
// If required JPAEntityType and related would need to implement Bindable
throw new NotImplementedException();
}
/**
* Return the parent "node" in the path or null if no parent.
* @return parent
*/
@Override
public Path<?> getParentPath() {
return parent.orElse(null);
}
@Override
public String toString() {
return "PathImpl [path=" + path + ", parent=" + parent + ", st=" + st + "]";
}
/**
* Create an expression corresponding to the type of the path.
* @return expression corresponding to the type of the path
*/
@Override
public Expression<Class<? extends X>> type() {
throw new NotImplementedException();
}
List<JPAPath> getPathList() {
return Arrays.asList(path.orElseThrow(IllegalStateException::new));
}
private String tableAliasFromParent(Optional<String> alias) {
if (parent.isPresent()) {
if (path.isPresent() && parent.get() instanceof FromImpl<?, ?> from) {
return from.getAlias(path.get()).orElse(alias.orElse(null));
} else {
return parent.get().tableAlias.orElse(alias.orElse(null));
}
}
return alias.orElse(null);
}
@SuppressWarnings("unchecked")
List<Path<Object>> resolvePathElements() {
if (path.isPresent())
return singletonList((Path<Object>) this);
return getPathList()
.stream()
.map(jpaPath -> new PathImpl<>(jpaPath, parent, st, tableAlias))
.collect(toList()); // NOSONAR
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((!path.isPresent()) ? 0 : path.hashCode());
result = prime * result + ((!tableAlias.isPresent()) ? 0 : tableAlias.hashCode());
return result;
}
@Override
public boolean equals(final Object object) {
return (object instanceof final PathImpl<?> otherPath)
&& (path.isEmpty() && otherPath.path.isEmpty()
|| path.isPresent() && path.equals(otherPath.path))
&& (tableAlias.isEmpty() && otherPath.tableAlias.isEmpty()
|| tableAlias.isPresent() && tableAlias.equals(otherPath.tableAlias));
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TypedQueryImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TypedQueryImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import jakarta.persistence.EntityManager;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.LockTimeoutException;
import jakarta.persistence.NoResultException;
import jakarta.persistence.NonUniqueResultException;
import jakarta.persistence.Parameter;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.PessimisticLockException;
import jakarta.persistence.Query;
import jakarta.persistence.QueryTimeoutException;
import jakarta.persistence.TemporalType;
import jakarta.persistence.TransactionRequiredException;
import jakarta.persistence.Tuple;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaQuery;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.cb.ProcessorSelection;
class TypedQueryImpl<T> extends AbstractQueryImpl implements TypedQuery<T> {
private final CriteriaQueryImpl<T> parent;
private final ProcessorSelection<T> selection;
private final EntityManager em;
TypedQueryImpl(final CriteriaQuery<T> criteriaQuery, final EntityManager em,
final ParameterBuffer parameterBuffer) {
super(parameterBuffer);
this.parent = (CriteriaQueryImpl<T>) criteriaQuery;
this.parent.getResultType();
this.selection = (ProcessorSelection<T>) parent.getSelection();
this.em = em;
}
@Override
public int executeUpdate() {
return createNativeQuery().executeUpdate();
}
@Override
public int getFirstResult() {
return parent.getFirstResult();
}
@Override
public int getMaxResults() {
return parent.getMaxResults();
}
/**
* Execute a SELECT query and return the query results as a typed List.
* @return a list of the results
* @throws IllegalStateException if called for a Java
* Persistence query language UPDATE or DELETE statement
* @throws QueryTimeoutException if the query execution exceeds
* the query timeout value set and only the statement is
* rolled back
* @throws TransactionRequiredException if a lock mode other than
* <code>NONE</code> has been set and there is no transaction
* or the persistence context has not been joined to the
* transaction
* @throws PessimisticLockException if pessimistic locking
* fails and the transaction is rolled back
* @throws LockTimeoutException if pessimistic locking
* fails and only the statement is rolled back
* @throws PersistenceException if the query execution exceeds
* the query timeout value set and the transaction
* is rolled back
*/
@SuppressWarnings("unchecked")
@Override
public List<T> getResultList() {
final List<?> result = createNativeQuery().getResultList();
if (parent.getResultType().isAssignableFrom(Tuple.class)) {
if (result.isEmpty())
return Collections.emptyList();
final List<Entry<String, JPAPath>> selectionPath = buildSelection();
final Map<String, Integer> index = buildSelectionIndex(selectionPath);
final List<Entry<String, JPAAttribute>> selectionAttributes = toAttributeList(selectionPath);
if (result.get(0).getClass().isArray()) {
return (List<T>) ((List<Object[]>) result).stream()
.map(item -> new TupleImpl(item, selectionAttributes, index))
.collect(Collectors.toList()); // NOSONAR
}
return (List<T>) ((List<Object>) result).stream()
.map(item -> new TupleImpl(item, selectionAttributes, index))
.collect(Collectors.toList()); // NOSONAR
}
return (List<T>) result;
}
/**
* Execute a SELECT query that returns a single untyped result.
* @return the result
* @throws NoResultException if there is no result
* @throws NonUniqueResultException if more than one result
* @throws IllegalStateException if called for a Java Persistence query language UPDATE or DELETE statement
* @throws QueryTimeoutException if the query execution exceeds
* the query timeout value set and only the statement is rolled back
* @throws TransactionRequiredException if a lock mode other than
* <code>NONE</code> has been set and there is no transaction
* or the persistence context has not been joined to the transaction
* @throws PessimisticLockException if pessimistic locking
* fails and the transaction is rolled back
* @throws LockTimeoutException if pessimistic locking
* fails and only the statement is rolled back
* @throws PersistenceException if the query execution exceeds
* the query timeout value set and the transaction
* is rolled back
*/
@Override
public T getSingleResult() {
final List<T> results = getResultList();
if (results.isEmpty())
throw new NoResultException();
if (results.size() > 1)
throw new NonUniqueResultException();
return results.get(0);
}
@Override
public TypedQuery<T> setFirstResult(final int startPosition) {
parent.setFirstResult(startPosition);
return this;
}
@Override
public TypedQuery<T> setFlushMode(final FlushModeType flushMode) {
super.setFlushMode(flushMode);
return this;
}
@Override
public TypedQuery<T> setHint(final String hintName, final Object value) {
super.setHint(hintName, value);
return this;
}
@Override
public TypedQuery<T> setLockMode(final LockModeType lockMode) {
super.setLockMode(lockMode);
return this;
}
@Override
public TypedQuery<T> setMaxResults(final int maxResult) {
this.parent.setMaxResults(maxResult);
return this;
}
/**
* Bind an instance of <code>java.util.Calendar</code> to a positional parameter.
* @throws IllegalStateException Setting parameter is not supported
*/
@Override
public TypedQuery<T> setParameter(final int position, final Calendar value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final int position, final Date value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final int position, final Object value) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final Parameter<Calendar> param, final Calendar value,
final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final Parameter<Date> param, final Date value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public <X> TypedQuery<T> setParameter(final Parameter<X> param, final X value) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final String name, final Calendar value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final String name, final Date value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public TypedQuery<T> setParameter(final String name, final Object value) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@SuppressWarnings("unchecked")
@Override
public <X> X unwrap(final Class<X> clazz) {
if (clazz.isAssignableFrom(this.getClass())) {
return (X) this;
}
if (clazz.isAssignableFrom(parent.getClass())) {
return (X) parent;
}
throw new PersistenceException("Unable to unwrap " + clazz.getName());
}
private List<Entry<String, JPAPath>> buildSelection() {
return selection.getResolvedSelection();
}
private Map<String, Integer> buildSelectionIndex(final List<Entry<String, JPAPath>> selectionPath) {
final int[] count = { 0 };
return selectionPath.stream()
.collect(Collectors.toMap(Entry::getKey, path -> count[0]++));
}
private List<Entry<String, JPAAttribute>> toAttributeList(final List<Entry<String, JPAPath>> selectionPath) {
final List<Entry<String, JPAAttribute>> result = new ArrayList<>(selectionPath.size());
for (final Entry<String, JPAPath> entity : selectionPath) {
result.add(new ProcessorSelection.SelectionAttribute(entity.getKey(), entity.getValue().getLeaf()));
}
return result;
}
private Query createNativeQuery() {
final StringBuilder sql = new StringBuilder();
final Query query = em.createNativeQuery(parent.asSQL(sql).toString());
query.setHint("eclipselink.cursor.scrollable", false); // https://wiki.eclipse.org/EclipseLink/Examples/JPA/Pagination#How_to_use_EclipseLink_Pagination
copyParameter(query);
return 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlJoinType.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlJoinType.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.EnumMap;
import jakarta.persistence.criteria.JoinType;
enum SqlJoinType {
INNER("INNER JOIN", JoinType.INNER),
LEFT("LEFT OUTER JOIN", JoinType.LEFT),
RIGHT("RIGHT OUTER JOIN", JoinType.RIGHT);
private static final EnumMap<JoinType, SqlJoinType> REL = new EnumMap<>(JoinType.class);
static SqlJoinType byJoinType(final JoinType jt) {
final SqlJoinType s = REL.get(jt);
if (s != null)
return s;
for (final SqlJoinType sql : SqlJoinType.values()) {
if (sql.getJoinType() == jt) {
REL.put(jt, sql);
return sql;
}
}
return null;
}
private final String keyWord;
private final JoinType jt;
private SqlJoinType(final String keyWord, final JoinType jt) {
this.keyWord = keyWord;
this.jt = jt;
}
JoinType getJoinType() {
return jt;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CompoundSelectionImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CompoundSelectionImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CompoundSelection;
import jakarta.persistence.criteria.Selection;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.cb.ProcessorSelection;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
final class CompoundSelectionImpl<X> implements CompoundSelection<X>, SqlSelection<X> {
private Optional<String> alias;
private final Class<X> resultType;
private final List<Selection<?>> rawSelections;
private Optional<List<Map.Entry<String, JPAPath>>> resolvedSelection = Optional.empty();
private Optional<List<Selection<?>>> selections = Optional.empty();
private final AliasBuilder aliasBuilder;
public CompoundSelectionImpl(final List<Selection<?>> selections, final Class<X> resultType,
final AliasBuilder aliasBuilder) {
this.resultType = resultType;
this.rawSelections = selections;
this.alias = Optional.empty();
this.aliasBuilder = aliasBuilder;
}
/**
* Assigns an alias to the selection item.
* Once assigned, an alias cannot be changed or reassigned.
* Returns the same selection item.
* @param name alias
* @return selection item
*/
@Override
public SqlSelection<X> alias(@Nonnull final String name) {
if (!alias.isPresent())
alias = Optional.of(name);
return this;
}
@Override
public StringBuilder asSQL(@Nonnull final StringBuilder statement) {
statement.append(getCompoundSelectionItems().stream()
.map(selection -> (Selection<?>) selection) // NOSONAR
.collect(new StringBuilderCollector.SelectionCollector(statement, ", ")));
return statement;
}
/**
* Return the alias assigned to the tuple element or null,
* if no alias has been assigned.
* @return alias
*/
@Override
public String getAlias() {
return alias.orElse("");
}
/**
* Return the selection items composing a compound selection.
* Modifications to the list do not affect the query.
* @return list of selection items
* @throws IllegalStateException if selection is not a
* compound selection
*/
@Override
public List<Selection<?>> getCompoundSelectionItems() {
return selections.orElseGet(this::asSelectionLate);
}
private List<Selection<?>> asSelectionLate() {
final List<Selection<?>> selectionItems = new ArrayList<>();
for (final Selection<?> sel : rawSelections) {
if (sel instanceof PathImpl<?>) {
selectionItems.addAll(((PathImpl<?>) sel)
.resolvePathElements()
.stream()
.map(element -> new SelectionImpl<>(element, element.getJavaType(), aliasBuilder))
.toList());
} else {
selectionItems.add(new SelectionImpl<>(sel, sel.getJavaType(), aliasBuilder));
}
}
selections = Optional.of(selectionItems);
return selections.get();
}
@Override
public Class<? extends X> getJavaType() {
return resultType;
}
@Override
public List<Entry<String, JPAPath>> getResolvedSelection() {
return resolvedSelection.orElseGet(this::resolveSelectionLate);
}
/**
* Whether the selection item is a compound selection.
* @return boolean indicating whether the selection is a compound
* selection
*/
@Override
public boolean isCompoundSelection() {
return true;
}
List<Map.Entry<String, JPAPath>> resolveSelectionLate() {
final AliasBuilder selectionAliasBuilder = new AliasBuilder("S");
final List<Map.Entry<String, JPAPath>> resolved = new ArrayList<>();
for (final Selection<?> sel : rawSelections) {
resolveSelectionItem(selectionAliasBuilder, resolved, sel);
}
resolvedSelection = Optional.of(resolved);
return resolvedSelection.get();
}
private void addSelectionList(final AliasBuilder aliasBuilder, final List<Map.Entry<String, JPAPath>> resolved,
final Selection<?> selection) {
if (selection instanceof final PathImpl<?> path) {
for (final JPAPath pathItem : path.getPathList()) {
resolved.add(new ProcessorSelection.SelectionItem(selection.getAlias().isEmpty()
? aliasBuilder.getNext() : (selection.getAlias() + "." + pathItem.getAlias()), pathItem));
}
} else {
throw new IllegalArgumentException("Not a path: " + selection.toString());
}
}
private void addSingleSelectionItem(final AliasBuilder aliasBuilder, final List<Map.Entry<String, JPAPath>> resolved,
final Selection<?> selection, final List<JPAPath> selectionItems) {
resolved.add(new ProcessorSelection.SelectionItem(selection.getAlias().isEmpty()
? aliasBuilder.getNext() : selection.getAlias(), selectionItems.get(0)));
}
private void resolveSelectionItem(final AliasBuilder aliasBuilder, final List<Map.Entry<String, JPAPath>> resolved,
final Selection<?> selection) {
if (selection instanceof PathImpl<?> || selection instanceof SelectionPath<?>) {
final List<JPAPath> selectionItems;
if (selection instanceof PathImpl<?>)
selectionItems = ((PathImpl<?>) selection).getPathList();
else
selectionItems = ((PathImpl<?>) ((SelectionPath<?>) selection).selection.getSelection()).getPathList();
if (selectionItems.size() == 1) {
addSingleSelectionItem(aliasBuilder, resolved, selection, selectionItems);
} else {
addSelectionList(aliasBuilder, resolved, selection);
}
} else {
resolved.add(new ProcessorSelection.SelectionItem(selection.getAlias().isEmpty()
? aliasBuilder.getNext() : selection.getAlias(), new JPAPathWrapper(selection)));
}
}
@Override
public Selection<X> getSelection() {
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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/OrderImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/OrderImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Optional;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Order;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
class OrderImpl implements Order, SqlConvertible {
private static final String SEPARATOR = ", ";
private static final int SEPARATOR_LENGTH = SEPARATOR.length();
private final boolean isAscending;
private final SqlConvertible expression;
OrderImpl(final boolean isAscending, final SqlConvertible expression) {
super();
this.isAscending = isAscending;
this.expression = expression;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
if (expression instanceof FromImpl<?, ?>)
return resolveExpression((FromImpl<?, ?>) expression, statement);
return expression.asSQL(statement).append(" ").append(isAscending ? SqlKeyWords.ASC : SqlKeyWords.DESC);
}
private StringBuilder resolveExpression(final FromImpl<?, ?> from, final StringBuilder statement) {
try {
from.st
.getKey()
.forEach(a -> {
try {
new PathImpl<>(from.st.getPath(a.getExternalName()), Optional.empty(), from.st, from.tableAlias)
.asSQL(statement)
.append(" ")
.append(isAscending ? SqlKeyWords.ASC : SqlKeyWords.DESC)
.append(SEPARATOR);
} catch (final ODataJPAModelException e) {
throw new InternalServerError(e);
}
});
return statement.delete(statement.length() - SEPARATOR_LENGTH, statement.length());
} catch (final ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
@Override
public Order reverse() {
return new OrderImpl(!isAscending, expression);
}
@Override
public boolean isAscending() {
return isAscending;
}
@Override
public Expression<?> getExpression() {
return (Expression<?>) expression;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SubqueryImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SubqueryImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.criteria.AbstractQuery;
import jakarta.persistence.criteria.CollectionJoin;
import jakarta.persistence.criteria.CommonAbstractCriteria;
import jakarta.persistence.criteria.CompoundSelection;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.ListJoin;
import jakarta.persistence.criteria.MapJoin;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.SetJoin;
import jakarta.persistence.criteria.Subquery;
import jakarta.persistence.metamodel.EntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaQuery;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
/**
* The <code>Subquery</code> interface defines functionality that is
* specific to subqueries.
*
* A subquery has an expression as its selection item.
*
* @author Oliver Grande
*
* @param <T> the type of the selection item.
*/
class SubqueryImpl<T> extends Pageable implements ProcessorSubquery<T>, SqlConvertible {
private final Class<T> type;
private final CommonAbstractCriteria parent;
private final ProcessorCriteriaQuery<T> inner;
SubqueryImpl(@Nonnull final Class<T> type, @Nonnull final CommonAbstractCriteria parent,
final AliasBuilder aliasBuilder,
final CriteriaBuilder cb, final ProcessorSqlPatternProvider sqlPattern, final JPAServiceDocument sd) {
super(sqlPattern);
this.type = Objects.requireNonNull(type);
this.parent = Objects.requireNonNull(parent);
this.inner = new CriteriaQueryImpl<>(type, sd, aliasBuilder, cb, sqlPattern);
}
@Override
public Subquery<T> select(@Nonnull final Expression<T> expression) {
inner.select(expression);
return this;
}
@Override
public Subquery<T> where(@Nonnull final Expression<Boolean> restriction) {
inner.where(restriction);
return this;
}
@Override
public Subquery<T> where(@Nonnull final Predicate... restrictions) {
inner.where(restrictions);
return this;
}
@Override
public Subquery<T> groupBy(@Nonnull final Expression<?>... grouping) {
inner.groupBy(grouping);
return this;
}
@Override
public Subquery<T> groupBy(@Nonnull final List<Expression<?>> grouping) {
inner.groupBy(grouping);
return this;
}
@Override
public Subquery<T> having(@Nonnull final Expression<Boolean> restriction) {
inner.having(restriction);
return this;
}
@Override
public Subquery<T> having(@Nonnull final Predicate... restrictions) {
inner.having(restrictions);
return this;
}
@Override
public Subquery<T> distinct(@Nonnull final boolean distinct) {
inner.distinct(distinct);
return this;
}
/**
* Create a subquery root correlated to a root of the
* enclosing query.
* @param parentRoot a root of the containing query
* @return subquery root
*/
@Override
public <Y> Root<Y> correlate(@Nonnull final Root<Y> parentRoot) {
throw new NotImplementedException();
}
@Override
public <X, Y> Join<X, Y> correlate(@Nonnull final Join<X, Y> parentJoin) {
throw new NotImplementedException();
}
@Override
public <X, Y> CollectionJoin<X, Y> correlate(@Nonnull final CollectionJoin<X, Y> parentCollection) {
throw new NotImplementedException();
}
@Override
public <X, Y> SetJoin<X, Y> correlate(@Nonnull final SetJoin<X, Y> parentSet) {
throw new NotImplementedException();
}
@Override
public <X, Y> ListJoin<X, Y> correlate(@Nonnull final ListJoin<X, Y> parentList) {
throw new NotImplementedException();
}
@Override
public <X, K, V> MapJoin<X, K, V> correlate(@Nonnull final MapJoin<X, K, V> parentMap) {
throw new NotImplementedException();
}
/**
* Return the query of which this is a subquery.
* This must be a CriteriaQuery or a Subquery.
* Not supported for subqueries of update or delete
* @return the enclosing query or subquery
*/
@Override
public AbstractQuery<?> getParent() {
if (!(parent instanceof AbstractQuery))
throw new IllegalStateException("Only supported for sub-queries of queries");
return (AbstractQuery<?>) parent;
}
@Override
public CommonAbstractCriteria getContainingQuery() {
return getParent();
}
/**
* Return the selection expression.
* @return the item to be returned in the subquery result
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Expression<T> getSelection() {
return (Expression<T>) ((SelectionImpl) inner.getSelection()).selection;
}
@Override
public Set<Join<?, ?>> getCorrelatedJoins() {
throw new NotImplementedException();
}
@Override
public <X> Root<X> from(@Nonnull final Class<X> entityClass) {
return inner.from(entityClass);
}
@Override
public <X> Root<X> from(@Nonnull final EntityType<X> entity) {
return inner.from(entity);
}
@Override
public Set<Root<?>> getRoots() {
return inner.getRoots();
}
@Override
public List<Expression<?>> getGroupList() {
return inner.getGroupList();
}
@Override
public Predicate getGroupRestriction() {
return inner.getGroupRestriction();
}
@Override
public boolean isDistinct() {
return inner.isDistinct();
}
@Override
public Class<T> getResultType() {
return type;
}
@Override
public <U> ProcessorSubquery<U> subquery(@Nonnull final Class<U> type) {
return inner.subquery(type);
}
/**
* Return the predicate that corresponds to the where clause
* restriction(s), or null if no restrictions have been
* specified.
* @return where clause predicate
*/
@Override
public Predicate getRestriction() {
return inner.getRestriction();
}
@Override
public Predicate isNull() {
throw new NotImplementedException();
}
@Override
public Predicate isNotNull() {
throw new NotImplementedException();
}
@Override
public Predicate in(@Nonnull final Object... values) {
throw new NotImplementedException();
}
@Override
public Predicate in(@Nonnull final Expression<?>... values) {
throw new NotImplementedException();
}
@Override
public Predicate in(@Nonnull final Collection<?> values) {
throw new NotImplementedException();
}
@Override
public Predicate in(@Nonnull final Expression<Collection<?>> values) {
throw new NotImplementedException();
}
@Override
public <X> Expression<X> as(@Nonnull final Class<X> type) {
throw new NotImplementedException();
}
@Override
public Selection<T> alias(@Nonnull final String name) {
throw new NotImplementedException();
}
/**
* Whether the selection item is a compound selection.
* @return boolean indicating whether the selection is a compound
* selection
*/
@Override
public boolean isCompoundSelection() {
return inner.getSelection() instanceof CompoundSelection;
}
/**
* Return the selection items composing a compound selection.
* Modifications to the list do not affect the query.
* <p>
* Star selections are not resolved currently!
* @return list of selection items
* @throws IllegalStateException if selection is not a
* compound selection
*/
@Override
public List<Selection<?>> getCompoundSelectionItems() {
if (isCompoundSelection()) {
return new ArrayList<>(((CompoundSelection<?>) inner.getSelection()).getCompoundSelectionItems());
} else if (inner.getSelection() != null) {
final Selection<T> selection = inner.getSelection();
if (selection.isCompoundSelection())
return new ArrayList<>(selection.getCompoundSelectionItems());
else
return singletonList(inner.getSelection());
} else {
return emptyList();
}
}
@Override
public Class<? extends T> getJavaType() {
return getResultType();
}
@Override
public String getAlias() {
throw new NotImplementedException();
}
@Override
public ProcessorSubquery<T> setMaxResults(@Nullable final Integer maxResult) {
super.setNumberOfResults(maxResult);
return this;
}
@Override
public ProcessorSubquery<T> setFirstResult(final Integer startPosition) {
super.setStartResult(startPosition);
return this;
}
@Override
public StringBuilder asSQL(@Nonnull final StringBuilder statement) {
var innerSql = ((SqlConvertible) inner).asSQL(statement);
paging(innerSql);
return innerSql;
}
@Override
public ProcessorSubquery<T> multiselect(final Selection<?>... selections) {
inner.multiselect(selections);
return this;
}
@Override
public ProcessorSubquery<T> multiselect(final List<Selection<?>> selectionList) {
inner.multiselect(selectionList);
return this;
}
@Override
public ProcessorSubquery<T> orderBy(final List<Order> o) {
inner.orderBy(o);
return this;
}
@Override
public ProcessorSubquery<T> orderBy(final Order... o) {
inner.orderBy(o);
return this;
}
@SuppressWarnings("unchecked")
@Override
public <X> Root<X> from(final ProcessorSubquery<?> subquery) {
return (Root<X>) inner.from(subquery);
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/PathJoin.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/PathJoin.java | package com.sap.olingo.jpa.processor.cb.impl;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.metamodel.Attribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
class PathJoin<Z, X> extends AbstractJoinImp<Z, X> {
private final FromImpl<?, Z> parentFrom;
PathJoin(@Nonnull final FromImpl<?, Z> parent, @Nonnull final JPAPath joinAttribute,
@Nonnull final AliasBuilder aliasBuilder, @Nonnull final CriteriaBuilder cb) {
super(parent.st, parent, joinAttribute, aliasBuilder, cb);
this.parentFrom = parent;
}
/**
* Return the metamodel attribute corresponding to the join.
* @return metamodel attribute corresponding to the join
*/
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
/**
* Return the join type.
* @return join type
*/
@Override
public JoinType getJoinType() {
return JoinType.INNER;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
if (!getJoins().isEmpty()) {
statement.append(getJoins().stream().collect(new StringBuilderCollector.ExpressionCollector(statement, " ")));
}
return statement;
}
@SuppressWarnings("unchecked")
@Override
FromImpl<?, Z> determineParent() {
return parentFrom.determineParent();
}
@Override
Expression<Boolean> createInheritanceWhere() {
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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/InheritanceJoin.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/InheritanceJoin.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Objects;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.metamodel.Attribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
/**
* Represents a join for an inheritance relation. From sub-type to super-type
* @param <Z> the sub-type
* @param <X> the super-type
*
* @author Oliver Grande
* @since 2.4.0
* @created 21.10.2025
*
*/
class InheritanceJoin<Z, X> extends AbstractJoinImp<Z, X> {
private final JPAEntityType subType;
InheritanceJoin(@Nonnull final JPAEntityType subType, @Nonnull final From<?, Z> parent,
@Nonnull final AliasBuilder aliasBuilder, @Nonnull final CriteriaBuilder cb) {
super(getSuperType(subType), parent, aliasBuilder, cb);
this.subType = subType;
}
@Override
public Predicate getOn() {
if (on == null)
try {
createOn(subType.getInheritanceInformation().getJoinColumnsList(), subType);
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
return on;
}
@Nonnull
private static final JPAEntityType getSuperType(final JPAEntityType subType) {
try {
return Objects.requireNonNull((JPAEntityType) subType.getBaseType());
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
@Override
public JoinType getJoinType() {
return JoinType.INNER;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object other) {
return super.equals(other);
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/AliasBuilder.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/AliasBuilder.java | package com.sap.olingo.jpa.processor.cb.impl;
class AliasBuilder {
private static final String ALIAS_PREFIX = "E";
private int aliasCount = 0;
private final String prefix;
AliasBuilder() {
this(ALIAS_PREFIX);
}
AliasBuilder(final String prefix) {
this.prefix = prefix;
}
String getNext() {
return prefix + aliasCount++;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlStringFunctions.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlStringFunctions.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlStringFunctions {
LOWER("LOWER"),
UPPER("UPPER"),
TRIM("TRIM"),
LENGTH("LENGTH"),
SUBSTRING("SUBSTRING"),
CONCAT("CONCAT"),
LOCATE("LOCATE");
private final String keyWord;
private SqlStringFunctions(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlArithmetic.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlArithmetic.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlArithmetic {
SUM("+"),
PROD("*"),
DIFF("-"),
MOD("%"),
QUOT("/");
private String keyWord;
private SqlArithmetic(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlTimeFunctions.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlTimeFunctions.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlTimeFunctions {
TIMESTAMP("CURRENT_TIMESTAMP"),
DATE("CURRENT_DATE"),
TIME("CURRENT_TIME");
private String keyWord;
private SqlTimeFunctions(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlSelection.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlSelection.java | package com.sap.olingo.jpa.processor.cb.impl;
import jakarta.persistence.criteria.Selection;
import com.sap.olingo.jpa.processor.cb.ProcessorSelection;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
interface SqlSelection<X> extends ProcessorSelection<X>, SqlConvertible {
Selection<X> getSelection();
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlKeyWords.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlKeyWords.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlKeyWords {
ADD("ADD"),
ALL("ALL"),
AND("AND"),
ANY("ANY"),
ASC("ASC"),
BETWEEN("BETWEEN"),
COALESCE("COALESCE"),
CONTAINS("CONTAINS"),
DESC("DESC"),
DISTINCT("DISTINCT"),
ESCAPE("ESCAPE"),
EXISTS("EXISTS"),
FROM("FROM"),
GROUPBY("GROUP BY"),
HAVING("HAVING"),
IN("IN"),
LIKE("LIKE"),
MOD("MOD"),
NOT("NOT"),
ORDERBY("ORDER BY"),
OVER("OVER"),
PARTITION("PARTITION BY"),
SELECT("SELECT"),
SET("SET"),
SOME("SOME"),
UNION("UNION"),
UPDATE("UPDATE"),
WHERE("WHERE");
private final String keyWord;
private SqlKeyWords(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SimpleJoin.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SimpleJoin.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Objects;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.metamodel.Attribute;
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.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
/**
*
* @author Oliver Grande
* @since 1.0.0
* @created 21.11.2020
*
* @param <Z> the source type of the join
* @param <X> the target type of the join
*/
class SimpleJoin<Z, X> extends AbstractJoinImp<Z, X> {
private final JoinType joinType;
final JPAAssociationPath association;
SimpleJoin(@Nonnull final JPAAssociationPath path, @Nonnull final JoinType jt,
@Nonnull final From<?, Z> parent, @Nonnull final AliasBuilder aliasBuilder, @Nonnull final CriteriaBuilder cb)
throws ODataJPAModelException {
super((JPAEntityType) path.getTargetType(), parent, aliasBuilder, cb);
this.joinType = jt;
this.association = path;
createOn(association.getJoinColumnsList(), (JPAEntityType) association.getTargetType());
}
/**
* Return the metamodel attribute corresponding to the join.
* @return metamodel attribute corresponding to the join
*/
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
/**
* Return the join type.
* @return join type
*/
@Override
public JoinType getJoinType() {
return joinType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(association, joinType);
return result;
}
@Override
public boolean equals(final Object object) {
return object instanceof SimpleJoin<?, ?> other
&& Objects.equals(association, other.association)
&& joinType == other.joinType;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CriteriaQueryImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CriteriaQueryImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
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.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.ParameterExpression;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Predicate.BooleanOperator;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.metamodel.EntityType;
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.ProcessorCriteriaQuery;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.ProcessorSubquery;
import com.sap.olingo.jpa.processor.cb.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.ExpressionCollector;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
class CriteriaQueryImpl<T> extends Pageable implements ProcessorCriteriaQuery<T>, SqlConvertible {
private final Class<T> resultType;
private final Set<FromImpl<?, ?>> roots = new HashSet<>();
private final JPAServiceDocument sd;
private SqlSelection<?> selection;
private Optional<Expression<Boolean>> where;
private boolean distinct;
private final AliasBuilder aliasBuilder;
private final AliasBuilder selectAliasBuilder;
private Optional<List<Order>> orderList;
private Optional<List<Expression<?>>> groupBy;
private Optional<Expression<Boolean>> having;
private final CriteriaBuilder cb;
CriteriaQueryImpl(final Class<T> clazz, final JPAServiceDocument sd, final AliasBuilder ab,
final CriteriaBuilder cb, final ProcessorSqlPatternProvider sqlPattern) {
super(sqlPattern);
this.resultType = clazz;
this.sd = sd;
this.where = Optional.empty();
this.orderList = Optional.empty();
this.groupBy = Optional.empty();
this.having = Optional.empty();
this.aliasBuilder = ab;
this.cb = cb;
this.selectAliasBuilder = new AliasBuilder("S");
}
CriteriaQueryImpl(final Class<T> clazz, final JPAServiceDocument sd, final CriteriaBuilder cb,
final ProcessorSqlPatternProvider sqlPattern) {
this(clazz, sd, new AliasBuilder(), cb, sqlPattern);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
final List<Expression<Boolean>> filterExpressions = new ArrayList<>();
where.ifPresent(filterExpressions::add);
roots.stream().forEach(r -> addInheritanceWhere(r, filterExpressions));
where = Optional.ofNullable(filterExpressions.stream().filter(Objects::nonNull).collect(new ExpressionCollector(
cb, BooleanOperator.AND)));
statement.append(SqlKeyWords.SELECT)
.append(" ")
.append(addDistinct());
selection.asSQL(statement);
statement.append(" ")
.append(SqlKeyWords.FROM)
.append(" ");
statement.append(roots.stream().collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
where.ifPresent(e -> {
statement.append(" ")
.append(SqlKeyWords.WHERE)
.append(" ");
((SqlConvertible) e).asSQL(statement);
});
groupBy.ifPresent(g -> {
statement.append(" ").append(SqlKeyWords.GROUPBY).append(" ");
statement.append(g.stream().collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
});
orderList.ifPresent(l -> {
statement.append(" ").append(SqlKeyWords.ORDERBY).append(" ");
statement.append(l.stream().collect(new StringBuilderCollector.OrderCollector(statement, ", ")));
});
having.ifPresent(e -> {
statement.append(" ")
.append(SqlKeyWords.HAVING)
.append(" ");
((SqlConvertible) e).asSQL(statement);
});
paging(statement);
return statement;
}
@Override
public CriteriaQuery<T> distinct(final boolean distinct) {
this.distinct = distinct;
return this;
}
@Override
public <X> Root<X> from(final Class<X> entityClass) {
try {
final JPAEntityType et = sd.getEntity(entityClass);
final Root<X> root = new RootImpl<>(et, aliasBuilder, cb);
roots.add((FromImpl<?, ?>) root);
return root;
} catch (final ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
@Override
public <X> Root<X> from(final EntityType<X> entity) {
return from(entity.getJavaType());
}
@Override
public <X> Root<X> from(@Nonnull final ProcessorSubquery<X> inner) {
try {
final Root<X> root = new SubqueryRootImpl<>(inner, aliasBuilder, sd);
roots.add((FromImpl<?, ?>) root);
return root;
} catch (final ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
/**
* Return a list of the grouping expressions. Returns empty
* list if no grouping expressions have been specified.
* Modifications to the list do not affect the query.
* @return the list of grouping expressions
*/
@Override
public List<Expression<?>> getGroupList() {
return groupBy.orElse(emptyList());
}
/**
* Return the predicate that corresponds to the restriction(s)
* over the grouping items, or null if no restrictions have
* been specified.
* @return having clause predicate
*/
@Override
public Predicate getGroupRestriction() {
return (Predicate) having.orElse(null);
}
@Override
public List<Order> getOrderList() {
return orderList.orElse(emptyList());
}
@Override
public Set<ParameterExpression<?>> getParameters() {
return emptySet();
}
/**
* Return the predicate that corresponds to the where clause
* restriction(s), or null if no restrictions have been
* specified.
* @return where clause predicate
*/
@Override
public Predicate getRestriction() {
return (Predicate) where.orElse(null);
}
@Override
public Class<T> getResultType() {
return resultType;
}
@Override
public Set<Root<?>> getRoots() {
return roots.stream()
.map(r -> (Root<?>) r) // NOSONAR
.collect(Collectors.toSet());
}
@SuppressWarnings("unchecked")
@Override
public Selection<T> getSelection() {
return (Selection<T>) selection;
}
/**
* Specify the expressions that are used to form groups over
* the query results.
* Replaces the previous specified grouping expressions, if any.
* If no grouping expressions are specified, any previously
* added grouping expressions are simply removed.
* This method only overrides the return type of the
* corresponding <code>AbstractQuery</code> method.
* @param grouping zero or more grouping expressions
* @return the modified query
*/
@Override
public CriteriaQuery<T> groupBy(final Expression<?>... grouping) {
return groupBy(grouping != null ? Arrays.asList(grouping) : emptyList());
}
/**
* Specify the expressions that are used to form groups over
* the query results.
* Replaces the previous specified grouping expressions, if any.
* If no grouping expressions are specified, any previously
* added grouping expressions are simply removed.
* This method only overrides the return type of the
* corresponding <code>AbstractQuery</code> method.
* @param grouping list of zero or more grouping expressions
* @return the modified query
*/
@Override
public CriteriaQuery<T> groupBy(final List<Expression<?>> grouping) {
groupBy = Optional.ofNullable(grouping.isEmpty() ? null : grouping);
return this;
}
/**
* Specify a restriction over the groups of the query.
* Replaces the previous having restriction(s), if any.
* This method only overrides the return type of the
* corresponding <code>AbstractQuery</code> method.
* @param restriction a simple or compound boolean expression
* @return the modified query
*/
@Override
public CriteriaQuery<T> having(final Expression<Boolean> restriction) {
final Predicate[] predicate = { (Predicate) restriction };
return having(predicate); // NOSONAR
}
/**
* Specify restrictions over the groups of the query
* according the conjunction of the specified restriction
* predicates.
* Replaces the previously added having restriction(s), if any.
* If no restrictions are specified, any previously added
* restrictions are simply removed.
* This method only overrides the return type of the
* corresponding <code>AbstractQuery</code> method.
* @param restrictions zero or more restriction predicates
* @return the modified query
*/
@Override
public CriteriaQuery<T> having(final Predicate... restrictions) {
final Predicate predicate = restrictions.length > 1
? cb.and(restrictions)
: restrictions.length == 1 // NOSONAR
? restrictions[0]
: null;
having = Optional.ofNullable(predicate);
return this;
}
@Override
public boolean isDistinct() {
return distinct;
}
/**
* Specify the selection items that are to be returned in the
* query result.
* Replaces the previously specified selection(s), if any.
*
* The type of the result of the query execution depends on
* the specification of the type of the criteria query object
* created as well as the arguments to the multiselect method.
* <p>
* An argument to the multiselect method must not be a tuple-
* or array-valued compound selection item.
*
* <p>
* The semantics of this method are as follows:
* <ul>
* <li>
* If the type of the criteria query is
* <code>CriteriaQuery<Tuple></code> (i.e., a criteria
* query object created by either the
* <code>createTupleQuery</code> method or by passing a
* <code>Tuple</code> class argument to the
* <code>createQuery</code> method), a <code>Tuple</code> object
* corresponding to the arguments of the <code>multiselect</code>
* method, in the specified order, will be instantiated and
* returned for each row that results from the query execution.
*
* <li>If the type of the criteria query is <code>CriteriaQuery<X></code> for
* some user-defined class X (i.e., a criteria query object
* created by passing a X class argument to the <code>createQuery</code>
* method), the arguments to the <code>multiselect</code> method will be
* passed to the X constructor and an instance of type X will be
* returned for each row.
*
* <li>If the type of the criteria query is <code>CriteriaQuery<X[]></code> for
* some class X, an instance of type X[] will be returned for
* each row. The elements of the array will correspond to the
* arguments of the <code>multiselect</code> method, in the
* specified order.
*
* <li>If the type of the criteria query is <code>CriteriaQuery<Object></code>
* or if the criteria query was created without specifying a
* type, and only a single argument is passed to the <code>multiselect</code>
* method, an instance of type <code>Object</code> will be returned for
* each row.
*
* <li>If the type of the criteria query is <code>CriteriaQuery<Object></code>
* or if the criteria query was created without specifying a
* type, and more than one argument is passed to the <code>multiselect</code>
* method, an instance of type <code>Object[]</code> will be instantiated
* and returned for each row. The elements of the array will
* correspond to the arguments to the <code> multiselect</code> method,
* in the specified order.
* </ul>
*
* @param selections selection items corresponding to the
* results to be returned by the query
* @return the modified query
* @throws IllegalArgumentException if a selection item is
* not valid or if more than one selection item has
* the same assigned alias
*/
@Override
public CriteriaQuery<T> multiselect(final List<Selection<?>> selectionList) {
selection = new CompoundSelectionImpl<>(selectionList, resultType, selectAliasBuilder);
return this;
}
@Override
public CriteriaQuery<T> multiselect(final Selection<?>... selections) {
return multiselect(Arrays.asList(selections));
}
/**
* Specify the ordering expressions that are used to
* order the query results.
* Replaces the previous ordering expressions, if any.
* If no ordering expressions are specified, the previous
* ordering, if any, is simply removed, and results will
* be returned in no particular order.
* The order of the ordering expressions in the list
* determines the precedence, whereby the first element in the
* list has highest precedence.
* @param o list of zero or more ordering expressions
* @return the modified query
*/
@Override
public CriteriaQuery<T> orderBy(final List<Order> o) {
if (o != null && o.isEmpty())
this.orderList = Optional.empty();
else
this.orderList = Optional.ofNullable(o);
return this;
}
@Override
public CriteriaQuery<T> orderBy(final Order... o) {
if (o == null) {
this.orderList = Optional.empty();
return this;
}
return this.orderBy(Arrays.asList(o));
}
@Override
public CriteriaQuery<T> select(final Selection<? extends T> selection) {
this.selection = new SelectionImpl<>(selection, resultType, selectAliasBuilder);
return this;
}
@Override
public <U> ProcessorSubquery<U> subquery(@Nonnull final Class<U> type) {
return new SubqueryImpl<>(type, this, aliasBuilder, cb, sqlPattern, sd);
}
/**
* Modify the query to restrict the query result according
* to the specified boolean expression.
* Replaces the previously added restriction(s), if any. <br>
* This method overrides the return type of the
* corresponding <code>AbstractQuery</code> method;
* @param restriction a simple or compound boolean expression
* @return the modified query
*/
@Override
public CriteriaQuery<T> where(@Nullable final Expression<Boolean> restriction) {
where = Optional.ofNullable(restriction);
return this;
}
/**
* Modify the query to restrict the query result according
* to the conjunction of the specified restriction predicates.
* Replaces the previously added restriction(s), if any.
* If no restrictions are specified, any previously added
* restrictions are simply removed.
* This method only overrides the return type of the
* corresponding <code>AbstractQuery</code> method.
* @param restrictions zero or more restriction predicates
* @return the modified query
*/
@Override
public CriteriaQuery<T> where(final Predicate... restrictions) {
throw new NotImplementedException();
}
JPAServiceDocument getServiceDocument() {
return sd;
}
private String addDistinct() {
if (distinct)
return SqlKeyWords.DISTINCT + " ";
return "";
}
private void addInheritanceWhere(final FromImpl<?, ?> from, final List<Expression<Boolean>> inheritanceWhere) {
inheritanceWhere.add(from.createInheritanceWhere());
for (final Join<?, ?> join : from.getJoins()) {
addInheritanceWhere((FromImpl<?, ?>) join, inheritanceWhere);
}
}
/**
* The position of the first result the query object was set to
* retrieve. Returns 0 if <code>setFirstResult</code> was not applied to the
* query object.
* @return position of the first result
* @since 2.0
*/
@Override
public int getFirstResult() {
return super.getStartResult();
}
@Override
public void setFirstResult(final int startPosition) {
super.setStartResult(startPosition);
}
/**
* The maximum number of results the query object was set to
* retrieve. Returns <code>Integer.MAX_VALUE</code> if <code>setMaxResults</code> was not
* applied to the query object.
* @return maximum number of results
* @since 2.0
*/
@Override
public int getMaxResults() {
return super.getMaxResults();
}
@Override
public void setMaxResults(final int maxResult) {
super.setNumberOfResults(maxResult);
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlPagingFunctions.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlPagingFunctions.java | package com.sap.olingo.jpa.processor.cb.impl;
import static com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider.VALUE_PLACEHOLDER;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
enum SqlPagingFunctions {
LIMIT(Integer.MAX_VALUE),
OFFSET(0);
private final int defaultValue;
private SqlPagingFunctions(final int defaultValue) {
this.defaultValue = defaultValue;
}
public String toString(final ProcessorSqlPatternProvider sqlPattern, final Integer value) {
if (this == LIMIT) {
return sqlPattern.getMaxResultsPattern().replace(VALUE_PLACEHOLDER, value.toString());
}
return sqlPattern.getFirstResultPattern().replace(VALUE_PLACEHOLDER, value.toString());
}
int defaultValue() {
return defaultValue;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/RootImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/RootImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.metamodel.EntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
class RootImpl<X> extends FromImpl<X, X> implements Root<X> {
RootImpl(final JPAEntityType type, final AliasBuilder aliasBuilder, final CriteriaBuilder cb) {
super(type, aliasBuilder, cb);
}
@Override
public EntityType<X> getModel() {
throw new NotImplementedException();
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/Pageable.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/Pageable.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Optional;
import javax.annotation.Nullable;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
abstract class Pageable {
final ProcessorSqlPatternProvider sqlPattern;
private Optional<Integer> maxResults;
private Optional<Integer> firstResult;
Pageable(ProcessorSqlPatternProvider sqlPattern) {
super();
this.sqlPattern = sqlPattern;
this.firstResult = Optional.empty();
this.maxResults = Optional.empty();
}
/**
* The position of the first result the query object was set to
* retrieve. Returns 0 if <code>setFirstResult</code> was not applied to the
* query object.
* @return position of the first result
*/
int getStartResult() {
return firstResult.orElse(0);
}
void setStartResult(@Nullable final Integer startPosition) {
firstResult = Optional.ofNullable(startPosition);
}
/**
* The maximum number of results the query object was set to
* retrieve. Returns <code>Integer.MAX_VALUE</code> if <code>setMaxResults</code> was not
* applied to the query object.
* @return maximum number of results
* @since 2.0
*/
int getMaxResults() {
return maxResults.orElse(Integer.MAX_VALUE);
}
void setNumberOfResults(@Nullable Integer maxResult) {
this.maxResults = Optional.ofNullable(maxResult);
}
void paging(final StringBuilder statement) {
if (sqlPattern.maxResultsFirst()) {
maxResults.ifPresent(limit -> statement.append(" ")
.append(SqlPagingFunctions.LIMIT.toString(sqlPattern, limit)));
firstResult.ifPresent(offset -> statement.append(" ")
.append(SqlPagingFunctions.OFFSET.toString(sqlPattern, offset)));
} else {
firstResult.ifPresent(offset -> statement.append(" ")
.append(SqlPagingFunctions.OFFSET.toString(sqlPattern, offset)));
maxResults.ifPresent(limit -> statement.append(" ")
.append(SqlPagingFunctions.LIMIT.toString(sqlPattern, limit)));
}
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlWindowFunctions.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlWindowFunctions.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlWindowFunctions {
ROW_NUMBER("ROW_NUMBER");
private String keyWord;
private SqlWindowFunctions(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/PredicateImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/PredicateImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
/**
*
* @author Oliver Grande
*
*/
abstract class PredicateImpl extends ExpressionImpl<Boolean> implements Predicate {
private static final int REQUIRED_NO_OPERATOR = 2;
protected final List<SqlConvertible> expressions;
static Predicate and(final Predicate[] restrictions) {
if (restrictions == null || arrayIsEmpty(restrictions, REQUIRED_NO_OPERATOR))
throw new IllegalArgumentException("Parameter 'restrictions' has to have at least 2 elements");
var predicate = restrictions[0];
for (int i = 1; i < restrictions.length; i++) {
predicate = new AndPredicate(predicate, restrictions[i]);
}
return predicate;
}
static Predicate or(final Predicate[] restrictions) {
if (restrictions == null || arrayIsEmpty(restrictions, REQUIRED_NO_OPERATOR))
throw new IllegalArgumentException("Parameter 'restrictions' has to have at least 2 elements");
var predicate = restrictions[0];
for (int i = 1; i < restrictions.length; i++) {
predicate = new OrPredicate(predicate, restrictions[i]);
}
return predicate;
}
private static boolean arrayIsEmpty(final Predicate[] restrictions, final int requiredNoElements) {
for (int i = 0; i < restrictions.length; i++) {
if (restrictions[i] == null)
return true;
}
return restrictions.length < requiredNoElements;
}
protected PredicateImpl(final SqlConvertible... expressions) {
super();
this.expressions = Collections.unmodifiableList(Arrays.asList(expressions));
}
@Override
public Selection<Boolean> alias(final String name) {
alias = Optional.ofNullable(name);
return this;
}
@Override
public <X> Expression<X> as(final Class<X> type) {
throw new NotImplementedException();
}
@Override
@CheckForNull
public String getAlias() {
return alias.orElse(null);
}
@Override
public List<Selection<?>> getCompoundSelectionItems() {
throw new NotImplementedException();
}
@Override
public List<Expression<Boolean>> getExpressions() {
return asExpression();
}
@Override
public Class<? extends Boolean> getJavaType() {
throw new NotImplementedException();
}
/**
* Whether the predicate has been created from another
* predicate by applying the <code>Predicate.not()</code> method
* or the <code>CriteriaBuilder.not()</code> method.
* @return boolean indicating if the predicate is
* a negated predicate
*/
@Override
public boolean isNegated() {
return false;
}
@Override
public Predicate not() {
return new NotPredicate(this);
}
@SuppressWarnings("unchecked")
private List<Expression<Boolean>> asExpression() {
return expressions.stream().map(expression -> (Expression<Boolean>) expression).toList();
}
@Override
public String toString() {
return "PredicateImpl [sql=" + asSQL(new StringBuilder()) + "]";
}
static class AndPredicate extends BooleanPredicate {
AndPredicate(final Expression<Boolean> x, final Expression<Boolean> y) {
super(x, y);
}
/**
* Return the boolean operator for the predicate.
* If the predicate is simple, this is <code>AND</code>.
* @return boolean operator for the predicate
*/
@Override
public BooleanOperator getOperator() {
return Predicate.BooleanOperator.AND;
}
}
static class BetweenExpressionPredicate extends PredicateImpl {
private final ExpressionImpl<?> attribute;
BetweenExpressionPredicate(final ExpressionImpl<?> attribute, final Expression<?> left, final Expression<?> right) {
super((SqlConvertible) left, (SqlConvertible) right);
this.attribute = attribute;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(OPENING_BRACKET);
this.attribute.asSQL(statement)
.append(" ")
.append(SqlKeyWords.BETWEEN)
.append(" ");
this.expressions.get(0).asSQL(statement)
.append(" ")
.append(SqlKeyWords.AND)
.append(" ");
return this.expressions.get(1).asSQL(statement).append(CLOSING_BRACKET);
}
@Override
public BooleanOperator getOperator() {
return null;
}
}
static class BinaryExpressionPredicate extends PredicateImpl {
private final Operation expression;
BinaryExpressionPredicate(final Operation operation, final Expression<?> left, final Expression<?> right) {
super((SqlConvertible) left, (SqlConvertible) right);
this.expression = operation;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(OPENING_BRACKET);
this.expressions.get(0).asSQL(statement)
.append(" ")
.append(expression)
.append(" ");
return this.expressions.get(1).asSQL(statement).append(CLOSING_BRACKET);
}
@Override
public BooleanOperator getOperator() {
return null;
}
enum Operation {
EQ("="), NE("<>"), GT(">"), GE(">="), LT("<"), LE("<=");
private final String keyWord;
private Operation(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
}
abstract static class BooleanPredicate extends PredicateImpl {
BooleanPredicate(final Expression<Boolean> x, final Expression<Boolean> y) {
super((SqlConvertible) x, (SqlConvertible) y);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(OPENING_BRACKET);
expressions.get(0).asSQL(statement)
.append(" ")
.append(getOperator())
.append(" ");
expressions.get(1).asSQL(statement);
statement.append(CLOSING_BRACKET);
return statement;
}
@Override
public String toString() {
return "AndPredicate [left=" + expressions.get(0) + ", right=" + expressions.get(1) + "]";
}
}
static class LikePredicate extends PredicateImpl {
private final ParameterExpression<String, ?> pattern;
private final Optional<ParameterExpression<Character, ?>> escape;
public LikePredicate(final Expression<String> column, final ParameterExpression<String, ?> pattern) {
this(column, pattern, Optional.empty());
}
public LikePredicate(final Expression<String> column, final ParameterExpression<String, ?> pattern,
final Optional<ParameterExpression<Character, ?>> escapeChar) {
super((SqlConvertible) column);
this.pattern = pattern;
this.escape = escapeChar;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(OPENING_BRACKET);
this.expressions.get(0).asSQL(statement)
.append(" ")
.append(SqlKeyWords.LIKE)
.append(" ");
this.pattern.asSQL(statement);
this.escape.ifPresent(esc -> statement
.append(" ")
.append(SqlKeyWords.ESCAPE)
.append(" "));
this.escape.ifPresent(esc -> esc.asSQL(statement));
return statement.append(CLOSING_BRACKET);
}
@Override
public BooleanOperator getOperator() {
return null;
}
}
static class NotPredicate extends PredicateImpl {
private final SqlConvertible positive;
NotPredicate(final SqlConvertible predicate) {
this.positive = predicate;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement
.append(OPENING_BRACKET)
.append(SqlKeyWords.NOT)
.append(" ");
return positive.asSQL(statement)
.append(CLOSING_BRACKET);
}
@Override
public BooleanOperator getOperator() {
return null;
}
@Override
public boolean isNegated() {
return true;
}
}
static class NullPredicate extends PredicateImpl {
private final SqlNullCheck check;
NullPredicate(@Nonnull final Expression<?> expression, @Nonnull final SqlNullCheck check) {
super((SqlConvertible) Objects.requireNonNull(expression));
this.check = Objects.requireNonNull(check);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
return expressions.get(0).asSQL(statement.append(OPENING_BRACKET))
.append(" ").append(check).append(CLOSING_BRACKET);
}
@Override
public BooleanOperator getOperator() {
return null;
}
}
static class OrPredicate extends BooleanPredicate {
OrPredicate(final Expression<Boolean> x, final Expression<Boolean> y) {
super(x, y);
}
/**
* Return the boolean operator for the predicate.
* If the predicate is simple, this is <code>AND</code>.
* @return boolean operator for the predicate
*/
@Override
public BooleanOperator getOperator() {
return Predicate.BooleanOperator.OR;
}
}
static class In<X> extends PredicateImpl implements CriteriaBuilder.In<X> {
private Optional<Expression<? extends X>> expression;
private Optional<List<ParameterExpression<X, X>>> values;
private ParameterBuffer parameter;
@SuppressWarnings("unchecked")
In(final List<Path<?>> paths, final Subquery<?> subquery) {
this(paths.stream().map(path -> (Path<Comparable<?>>) path).toList(), null);
this.expression = Optional.of((Expression<? extends X>) Objects.requireNonNull(subquery));
}
In(final List<Path<Comparable<?>>> paths, final ParameterBuffer parameter) {
super(new CompoundPathImpl(paths));
this.values = Optional.empty();
this.expression = Optional.empty();
this.parameter = parameter;
}
@SuppressWarnings("unchecked")
In(final Path<?> path, final ParameterBuffer parameter) {
this(Collections.singletonList((Path<Comparable<?>>) path), parameter);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
return expression.map(exp -> asSubQuerySQL(exp, statement))
.orElseGet(() -> values.map(list -> asFixValueSQL(list, statement))
.orElseThrow());
}
private StringBuilder asFixValueSQL(final List<ParameterExpression<X, X>> list, final StringBuilder statement) {
prepareInExpression(statement);
statement.append(list.stream()
.collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
return statement.append(CLOSING_BRACKET);
}
private StringBuilder asSubQuerySQL(final Expression<? extends X> exp, final StringBuilder statement) {
prepareInExpression(statement);
return ((SqlConvertible) Objects.requireNonNull(exp)).asSQL(statement).append(CLOSING_BRACKET);
}
private void prepareInExpression(final StringBuilder statement) {
expressions.get(0).asSQL(statement)
.append(" ")
.append(SqlKeyWords.IN)
.append(" ")
.append(OPENING_BRACKET);
}
@Override
public jakarta.persistence.criteria.CriteriaBuilder.In<X> value(final X value) {
if (this.expression.isPresent())
throw new IllegalStateException("Do not add a fixed value if an expression is already present");
values.ifPresentOrElse(list -> list.add(parameter.addValue(value)), () -> createValues(value));
return this;
}
private void createValues(final X value) {
// parameter.addValue(value)
values = Optional.of(new ArrayList<>());
values.get().add(parameter.addValue(value));
}
@Override
public jakarta.persistence.criteria.CriteriaBuilder.In<X> value(final Expression<? extends X> value) {
if (this.values.isPresent())
throw new IllegalStateException("Do not add an expression if a fixed value is already present");
if (this.expression.isPresent())
throw new NotImplementedException();
this.expression = Optional.of(Objects.requireNonNull(value));
return this;
}
@Override
public BooleanOperator getOperator() {
return BooleanOperator.AND;
}
@SuppressWarnings("unchecked")
@Override
public Expression<X> getExpression() {
final CompoundPath paths = ((CompoundPath) expressions.get(0));
return paths.isEmpty() ? null : (Expression<X>) paths.getFirst();
}
}
static class SubQuery extends PredicateImpl {
private final SqlConvertible query;
private final SqlSubQuery operator;
public SubQuery(@Nonnull final Subquery<?> subquery, @Nonnull final SqlSubQuery operator) {
this.query = (SqlConvertible) Objects.requireNonNull(subquery);
this.operator = operator;
}
@Override
public StringBuilder asSQL(@Nonnull final StringBuilder statement) {
statement.append(operator)
.append(" ")
.append(OPENING_BRACKET);
return query.asSQL(statement).append(CLOSING_BRACKET);
}
@Override
public BooleanOperator getOperator() {
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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CriteriaUpdateImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CriteriaUpdateImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaUpdate;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Subquery;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.SingularAttribute;
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.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.SetExpression;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
class CriteriaUpdateImpl<T> implements CriteriaUpdate<T>, SqlConvertible {
private final Class<T> targetEntity;
private final RootImpl<T> root;
private final AliasBuilder aliasBuilder;
private final CriteriaBuilder cb;
private final JPAServiceDocument sd;
private Optional<Expression<Boolean>> where;
private Optional<List<SetExpression>> set;
private final ParameterBuffer parameter;
private final ProcessorSqlPatternProvider sqlPattern;
CriteriaUpdateImpl(final JPAServiceDocument sd, final CriteriaBuilder cb, final ParameterBuffer parameterBuffer,
final Class<T> targetEntity, final ProcessorSqlPatternProvider sqlPattern) {
this.targetEntity = targetEntity;
this.aliasBuilder = new AliasBuilder();
this.parameter = parameterBuffer;
this.cb = cb;
this.sd = sd;
this.root = createRoot();
this.where = Optional.empty();
this.set = Optional.empty();
this.sqlPattern = sqlPattern;
}
private RootImpl<T> createRoot() {
try {
final JPAEntityType et = sd.getEntity(targetEntity);
return new RootImpl<>(et, aliasBuilder, cb);
} catch (final ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
/**
* Create a subquery of the query.
* @param type the subquery result type
* @return subquery
*/
@Override
public <U> Subquery<U> subquery(@Nonnull final Class<U> type) {
return new SubqueryImpl<>(type, this, aliasBuilder, cb, sqlPattern, sd);
}
/**
* Return the predicate that corresponds to the where clause
* restriction(s), or null if no restrictions have been
* specified.
* @return where clause predicate
*/
@Override
public Predicate getRestriction() {
throw new NotImplementedException();
}
/**
* Create and add a query root corresponding to the entity
* that is the target of the update.
* A <code>CriteriaUpdate</code> object has a single root, the entity that
* is being updated.
* @param entityClass the entity class
* @return query root corresponding to the given entity
*/
@Override
public Root<T> from(final Class<T> entityClass) {
return getRoot();
}
/**
* Create and add a query root corresponding to the entity
* that is the target of the update.
* A <code>CriteriaUpdate</code> object has a single root, the entity that
* is being updated.
* @param entity metamodel entity representing the entity
* of type X
* @return query root corresponding to the given entity
*/
@Override
public Root<T> from(final EntityType<T> entity) {
return getRoot();
}
/**
* Return the query root.
* @return the query root
*/
@Override
public Root<T> getRoot() {
return root;
}
@Override
public <Y, X extends Y> CriteriaUpdate<T> set(final SingularAttribute<? super T, Y> attribute, final X value) {
final Path<Y> path = getRoot().get(attribute.getName());
return set(path, value);
}
@Override
public <Y> CriteriaUpdate<T> set(final SingularAttribute<? super T, Y> attribute,
final Expression<? extends Y> value) {
final Path<Y> path = getRoot().get(attribute.getName());
return set(path, value);
}
/**
* Update the value of the specified attribute.
* @param attribute attribute to be updated
* @param value new value
* @return the modified update query
*/
@Override
public <Y, X extends Y> CriteriaUpdate<T> set(final Path<Y> attribute, final X value) {
return set(attribute, literal(value, attribute));
}
@Override
public <Y> CriteriaUpdate<T> set(final Path<Y> attribute, final Expression<? extends Y> value) {
set.ifPresentOrElse(sets -> sets.add(new SetValueExpression<>(attribute, value)),
() -> this.createSetList(attribute, value));
return this;
}
private <Y> Optional<List<SetExpression>> createSetList(final Path<Y> attribute,
final Expression<? extends Y> value) {
final List<SetExpression> sets = new ArrayList<>();
sets.add(new SetValueExpression<>(attribute, value));
set = Optional.of(sets);
return set;
}
@Override
public CriteriaUpdate<T> set(final String attributeName, final Object value) {
return set(getRoot().get(attributeName), value);
}
/**
* Modify the update query to restrict the target of the update
* according to the specified boolean expression.
* Replaces the previously added restriction(s), if any.
* @param restriction a simple or compound boolean expression
* @return the modified update query
*/
@Override
public CriteriaUpdate<T> where(final Expression<Boolean> restriction) {
where = Optional.ofNullable(restriction);
return this;
}
/**
* Modify the update query to restrict the target of the update
* according to the conjunction of the specified restriction
* predicates.
* Replaces the previously added restriction(s), if any.
* If no restrictions are specified, any previously added
* restrictions are simply removed.
* @param restrictions zero or more restriction predicates
* @return the modified update query
*/
@Override
public CriteriaUpdate<T> where(final Predicate... restrictions) {
throw new NotImplementedException();
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(SqlKeyWords.UPDATE)
.append(" ");
root.asSQL(statement);
set.ifPresent(list -> statement.append(" ")
.append(SqlKeyWords.SET)
.append(" ")
.append(list.stream()
.collect(new StringBuilderCollector.SetCollector(statement, ", "))));
where.ifPresent(a -> {
statement.append(" ")
.append(SqlKeyWords.WHERE)
.append(" ");
((SqlConvertible) a).asSQL(statement);
});
return statement;
}
private <X> Expression<X> literal(@Nonnull final X value, @Nonnull final Expression<? extends X> x) {
return parameter.addValue(value, x);
}
static record SetValueExpression<Y>(Path<Y> attribute, Expression<? extends Y> value) implements
SetExpression {
@Override
public StringBuilder asSQL(final StringBuilder statement) {
((SqlConvertible) attribute).asSQL(statement)
.append(" = ");
((SqlConvertible) value).asSQL(statement);
return statement;
}
}
ParameterBuffer getParameterBuffer() {
return parameter;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CompoundPath.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CompoundPath.java | package com.sap.olingo.jpa.processor.cb.impl;
import jakarta.persistence.criteria.Path;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
/**
*
* @author Oliver Grande
* @since 2.0.1
* @created 12.11.2023
*/
interface CompoundPath extends SqlConvertible {
boolean isEmpty();
<T> Path<T> getFirst() throws IllegalStateException;
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/JoinTableJoin.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/JoinTableJoin.java | package com.sap.olingo.jpa.processor.cb.impl;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.metamodel.Attribute;
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.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
class JoinTableJoin<Z, X> extends AbstractJoinImp<Z, X> {
private final JPAAssociationPath association;
private boolean inner = false;
@SuppressWarnings({ "unchecked", "rawtypes" })
JoinTableJoin(@Nonnull final JPAAssociationPath path, @Nonnull final JoinType jt,
@Nonnull final From<?, Z> parent, @Nonnull final AliasBuilder aliasBuilder, @Nonnull final CriteriaBuilder cb)
throws ODataJPAModelException {
super((JPAEntityType) path.getTargetType(), (From<?, Z>) new InnerJoin(parent, aliasBuilder, cb, path, jt),
aliasBuilder, cb);
this.association = path;
related.getJoins().add(this);
createOn(association.getJoinTable().getRawInverseJoinInformation());
}
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
@Override
public JoinType getJoinType() {
return JoinType.INNER;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj);
}
private static class InnerJoin<Z, X> extends AbstractJoinImp<Z, X> {
private final JoinType joinType;
private final JPAAssociationPath association;
public InnerJoin(final From<?, Z> parent, @Nonnull final AliasBuilder ab, @Nonnull final CriteriaBuilder cb,
@Nonnull final JPAAssociationPath path, final JoinType jt) {
super(path.getJoinTable().getEntityType(), parent, ab, cb);
this.joinType = jt;
this.association = path;
createOn(path.getJoinTable().getRawJoinInformation());
}
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
@Override
public JoinType getJoinType() {
return joinType;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(" ")
.append(SqlJoinType.byJoinType(getJoinType()))
.append(" ");
if (!getJoins().isEmpty())
statement.append(OPENING_BRACKET);
statement.append(association.getJoinTable().getTableName());
tableAlias.ifPresent(p -> statement.append(" ").append(p));
statement.append(getJoins().stream().collect(new StringBuilderCollector.ExpressionCollector(statement, " ")));
if (!getJoins().isEmpty())
statement.append(CLOSING_BRACKET);
statement.append(" ON ");
((SqlConvertible) on).asSQL(statement);
return statement;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(final Object obj) {
// As always a new alias is created super call is sufficant
return super.equals(obj);
}
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
if (inner) {
return super.asSQL(statement);
} else {
inner = true;
return ((SqlConvertible) related).asSQL(statement);
}
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CollectionJoinImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CollectionJoinImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.metamodel.Attribute;
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.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
class CollectionJoinImpl<Z, X> extends AbstractJoinImp<Z, X> {
private final JPACollectionAttribute attribute;
private final JoinType joinType;
CollectionJoinImpl(@Nonnull final JPAPath path, @Nonnull final FromImpl<?, Z> parent,
@Nonnull final AliasBuilder aliasBuilder, @Nonnull final CriteriaBuilder cb,
@Nullable final JoinType joinType) throws ODataJPAModelException {
super(determineEt(path, parent), parent, determinePath(path), aliasBuilder, cb);
this.attribute = (JPACollectionAttribute) path.getLeaf();
this.joinType = joinType;
createOn(attribute.asAssociation()
.getJoinTable()
.getRawJoinInformation());
}
private static JPAPath determinePath(final JPAPath path) throws ODataJPAModelException {
return ((JPACollectionAttribute) path.getLeaf())
.asAssociation()
.getTargetType() == null
? path : null;
}
private static JPAEntityType determineEt(@Nonnull final JPAPath path, @Nonnull final FromImpl<?, ?> parent)
throws ODataJPAModelException {
return (JPAEntityType) Optional.ofNullable(((JPACollectionAttribute) path.getLeaf())
.asAssociation()
.getTargetType())
.orElseThrow(() -> new IllegalStateException("Entity type for collection attribute '&1' of '&2' not found"
.replace("&1", path.getLeaf().getInternalName())
.replace("&2", parent.st.getInternalName())));
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
try {
statement.append(" ")
.append(SqlJoinType.byJoinType(getJoinType()))
.append(" ")
.append(attribute
.asAssociation()
.getJoinTable()
.getTableName());
tableAlias.ifPresent(alias -> statement.append(" ").append(alias));
statement.append(" ON ");
return ((SqlConvertible) on).asSQL(statement);
} catch (final ODataJPAModelException e) {
throw new IllegalStateException("Target DB table of collection attribute '&1' of '&2'"
.replace("&1", attribute.getInternalName())
.replace("&2", st.getInternalName()), e);
}
}
@Override
List<Path<Object>> resolvePathElements() {
final List<Path<Object>> pathList = new ArrayList<>();
try {
if (!attribute.isComplex()) {
final JPAStructuredType source = attribute.asAssociation().getSourceType();
final var associationPath = source.getPath(attribute.asAssociation().getAlias());
if (associationPath != null)
pathList.add(new PathImpl<>(associationPath, parent, st, tableAlias));
else
throw new IllegalStateException();
} else {
final JPAStructuredType source = attribute.getStructuredType();
for (final JPAPath p : source.getPathList()) {
pathList.add(new PathImpl<>(p, parent, st, tableAlias));
}
}
} catch (final ODataJPAModelException e) {
throw new IllegalStateException(e);
}
return pathList;
}
@Override
List<JPAPath> getPathList() {
final List<JPAPath> pathList = new ArrayList<>();
try {
if (!attribute.isComplex()) {
final JPAStructuredType source = attribute.asAssociation().getSourceType();
final JPAPath path = source.getPath(this.alias.orElse(attribute.getExternalName()));
pathList.add(path);
} else {
pathList.addAll(attribute.getStructuredType().getPathList().stream()
.filter(path -> !path.ignore())
.toList());
}
} catch (final ODataJPAModelException e) {
throw new IllegalStateException(e);
}
return pathList;
}
/**
* Return the metamodel attribute corresponding to the join.
* @return metamodel attribute corresponding to the join
*/
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
@Override
public JoinType getJoinType() {
return joinType == null ? JoinType.INNER : joinType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(attribute);
return result;
}
@Override
public boolean equals(final Object object) {
if (object instanceof final CollectionJoinImpl other)// NOSONAR
return Objects.equals(attribute, other.attribute);
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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlNullCheck.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlNullCheck.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlNullCheck {
NULL("IS NULL"),
NOT_NULL("IS NOT NULL");
private String keyWord;
private SqlNullCheck(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlSubQuery.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlSubQuery.java | package com.sap.olingo.jpa.processor.cb.impl;
enum SqlSubQuery {
EXISTS("EXISTS"),
SOME("SOME"),
ALL("ALL"),
ANY("ANY");
private String keyWord;
private SqlSubQuery(final String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return keyWord;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SubqueryRootImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SubqueryRootImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import jakarta.persistence.metamodel.EntityType;
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.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
class SubqueryRootImpl<X> extends FromImpl<X, X> implements Root<X> {
private final Subquery<X> query;
SubqueryRootImpl(@Nonnull final ProcessorSubquery<X> inner, @Nonnull final AliasBuilder aliasBuilder,
@Nonnull final JPAServiceDocument sd) throws ODataJPAModelException {
super(sd.getEntity(inner.getJavaType()), aliasBuilder, null);
this.query = inner;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(OPENING_BRACKET);
((SqlConvertible) query).asSQL(statement);
statement.append(CLOSING_BRACKET)
.append(" AS ")
.append(tableAlias
.orElseThrow(() -> new IllegalStateException("Missing table alias for a sub query in FROM clause")));
return statement;
}
@Override
public EntityType<X> getModel() {
throw new NotImplementedException();
}
/**
* @param attributeName name of the attribute
* @return path corresponding to the referenced attribute
* @throws IllegalStateException if invoked on a path that
* corresponds to a basic type
* @throws IllegalArgumentException if attribute of the given
* name does not otherwise exist
**/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <Y> Path<Y> get(final String attributeName) {
for (final Selection<?> selection : query.getCompoundSelectionItems()) {
if (selection instanceof final SelectionImpl<?> selectionImpl) {
final Selection<?> x = selectionImpl.selection;
if (x instanceof PathImpl<?>) {
if (x.getAlias().equals(attributeName)
|| ((PathImpl<?>) x).path
.orElseThrow(IllegalStateException::new)
.getAlias().equals(attributeName)
|| ((PathImpl<?>) x).path
.orElseThrow(IllegalStateException::new)
.getLeaf().getInternalName().equals(attributeName)) {
return new SelectionPath(selectionImpl, tableAlias);
}
} else if (x instanceof WindowFunctionExpression<?>
&& x.getAlias().equals(attributeName)) {
return ((WindowFunctionExpression<Y>) x).asPath(tableAlias.orElse(""));
}
}
}
return super.get(attributeName);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + query.hashCode();
return result;
}
@Override
public boolean equals(final Object object) {
return (object instanceof final SubqueryRootImpl<?> other)
&& super.equals(other)
&& query.equals(other.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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/AbstractJoinImp.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/AbstractJoinImp.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Predicate;
import com.sap.olingo.jpa.metadata.api.JPAJoinColumn;
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.processor.cb.impl.PredicateImpl.BinaryExpressionPredicate;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
abstract class AbstractJoinImp<Z, X> extends FromImpl<Z, X> implements Join<Z, X> {
protected Predicate on;
protected final From<?, Z> related;
AbstractJoinImp(@Nonnull final JPAEntityType type, @Nonnull final From<?, Z> parent,
@Nonnull final AliasBuilder ab, @Nonnull final CriteriaBuilder cb) {
super(type, ab, cb);
this.related = parent;
}
AbstractJoinImp(@Nonnull final JPAEntityType type, @Nonnull final From<?, Z> parent, final JPAPath path,
@Nonnull final AliasBuilder ab, @Nonnull final CriteriaBuilder cb) {
super(type, path, ab, cb);
this.related = parent;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(" ")
.append(SqlJoinType.byJoinType(getJoinType()))
.append(" ");
if (!getJoins().isEmpty())
statement.append(OPENING_BRACKET);
statement.append(st.getTableName());
tableAlias.ifPresent(p -> statement.append(" ").append(p));
statement.append(getJoins().stream().collect(new StringBuilderCollector.ExpressionCollector(statement, " ")));
if (!getJoins().isEmpty())
statement.append(CLOSING_BRACKET);
statement.append(" ON ");
((SqlConvertible) getOn()).asSQL(statement);
return statement;
}
/**
* Return the predicate that corresponds to the ON
* restriction(s) on the join, or null if no ON condition
* has been specified.
* @return the ON restriction predicate
* @since Java Persistence 2.1
*/
@Override
public Predicate getOn() {
return on;
}
/**
* Return the parent of the join.
* @return join parent
*/
@Override
public From<?, Z> getParent() {
return related;
}
/**
* Modify the join to restrict the result according to the
* specified ON condition and return the join object.
* Replaces the previous ON condition, if any.
* @param restriction a simple or compound boolean expression
* @return the modified join object
* @since Java Persistence 2.1
*/
@Override
public Join<Z, X> on(@Nonnull final Expression<Boolean> restriction) {
on = (Predicate) restriction;
return this;
}
/**
* Modify the join to restrict the result according to the
* specified ON condition and return the join object.
* Replaces the previous ON condition, if any.
* @param restrictions zero or more restriction predicates
* @return the modified join object
* @since Java Persistence 2.1
*/
@Override
public Join<Z, X> on(@Nonnull final Predicate... restrictions) {
on = PredicateImpl.and(restrictions);
return this;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(final Object other) {
return super.equals(other);
}
protected void createOn(final List<JPAOnConditionItem> items, final JPAEntityType targetType) {
for (final JPAOnConditionItem item : items) {
final Predicate eq = createOnElement(item, targetType);
if (on == null)
on = eq;
else
on = new PredicateImpl.AndPredicate(on, eq);
}
}
private Predicate createOnElement(final JPAOnConditionItem item, final JPAEntityType target) {
final Expression<?> left = new PathImpl<>(item.getLeftPath(), Optional.of((PathImpl<?>) related),
((PathImpl<?>) related).st, ((FromImpl<?, ?>) related).tableAlias);
final Expression<?> right = new PathImpl<>(item.getRightPath(), Optional.of(this),
target, tableAlias);
return new PredicateImpl.BinaryExpressionPredicate(PredicateImpl.BinaryExpressionPredicate.Operation.EQ, left,
right);
}
protected <T extends JPAJoinColumn> void createOn(final List<T> joinInformation) {
for (final JPAJoinColumn column : joinInformation) {
final Predicate eq = createOnElement(column);
if (on == null)
on = eq;
else
on = new PredicateImpl.AndPredicate(on, eq);
}
}
@SuppressWarnings("unchecked")
private BinaryExpressionPredicate createOnElement(final JPAJoinColumn column) {
return new PredicateImpl.BinaryExpressionPredicate(PredicateImpl.BinaryExpressionPredicate.Operation.EQ,
new ExpressionPath<>(column.getName(), ((FromImpl<Z, X>) related).tableAlias),
new ExpressionPath<>(column.getReferencedColumnName(), tableAlias));
}
} | 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CriteriaBuilderImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CriteriaBuilderImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nonnull;
import jakarta.persistence.Tuple;
import jakarta.persistence.criteria.CollectionJoin;
import jakarta.persistence.criteria.CompoundSelection;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.CriteriaUpdate;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.ListJoin;
import jakarta.persistence.criteria.MapJoin;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.SetJoin;
import jakarta.persistence.criteria.Subquery;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaQuery;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.impl.ExpressionImpl.ParameterExpression;
import com.sap.olingo.jpa.processor.cb.impl.PredicateImpl.BinaryExpressionPredicate.Operation;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
class CriteriaBuilderImpl implements ProcessorCriteriaBuilder { // NOSONAR
private final JPAServiceDocument sd;
private ParameterBuffer parameter;
private final ProcessorSqlPatternProvider sqlPattern;
CriteriaBuilderImpl(final JPAServiceDocument sd, final ProcessorSqlPatternProvider sqlPattern) {
this.sd = sd;
this.parameter = new ParameterBuffer();
this.sqlPattern = sqlPattern;
}
@Override
public ParameterBuffer getParameterBuffer() {
return parameter;
}
@Override
public void resetParameterBuffer() {
this.parameter = new ParameterBuffer();
}
/**
* Create an expression that returns the absolute value
* of its argument.
* @param x expression
* @return absolute value
*/
@Override
public <N extends Number> Expression<N> abs(@Nonnull final Expression<N> expression) {
throw new NotImplementedException();
}
/**
* Create an all expression over the subquery results.
* @param subquery subquery
* @return all expression
*/
@Override
public <Y> Expression<Y> all(@Nonnull final Subquery<Y> subquery) {
return new ExpressionImpl.SubQuery<>(subquery, SqlSubQuery.ALL);
}
@Override
public Predicate and(final Expression<Boolean> x, final Expression<Boolean> y) {
return new PredicateImpl.AndPredicate(x, y);
}
@Override
public Predicate and(final Predicate... restrictions) {
return PredicateImpl.and(restrictions);
}
/**
* Create an any expression over the subquery results.
* This expression is equivalent to a <code>some</code> expression.
* @param subquery subquery
* @return any expression
*/
@Override
public <Y> Expression<Y> any(@Nonnull final Subquery<Y> subquery) {
return new ExpressionImpl.SubQuery<>(subquery, SqlSubQuery.ANY);
}
/**
* Create an array-valued selection item.
* @param selections selection items
* @return array-valued compound selection
* @throws IllegalArgumentException if an argument is a
* tuple- or array-valued selection item
*/
@Override
public CompoundSelection<Object[]> array(@Nonnull final Selection<?>... selections) {
throw new NotImplementedException();
}
/**
* Create an ordering by the ascending value of the expression.
* @param x expression used to define the ordering
* @return ascending ordering corresponding to the expression
*/
@Override
public Order asc(@Nonnull final Expression<?> x) {
return new OrderImpl(true, Objects.requireNonNull((SqlConvertible) x));
}
/**
* Create an aggregate expression applying the avg operation.
* @param x expression representing input value to avg operation
* @return avg expression
*/
@Override
public <N extends Number> Expression<Double> avg(@Nonnull final Expression<N> x) {
throw new NotImplementedException();
}
/**
* Create a predicate for testing whether the first argument is
* between the second and third arguments in value.
* @param v expression
* @param x expression
* @param y expression
* @return between predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate between(@Nonnull final Expression<? extends Y> v,
@Nonnull final Expression<? extends Y> x, @Nonnull final Expression<? extends Y> y) {
return new PredicateImpl.BetweenExpressionPredicate((ExpressionImpl<?>) v, x, y);
}
/**
* Create a predicate for testing whether the first argument is
* between the second and third arguments in value.
* @param v expression
* @param x value
* @param y value
* @return between predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate between(@Nonnull final Expression<? extends Y> v,
@Nonnull final Y x, @Nonnull final Y y) {
return between(v, literal(x, v), literal(y, v));
}
/**
* Create a coalesce expression.
* @return coalesce expression
*/
@Override
public <T> Coalesce<T> coalesce() {
return new ExpressionImpl.CoalesceExpression<>();
}
/**
* Create an expression that returns null if all its arguments
* evaluate to null, and the value of the first non-null argument
* otherwise.
* @param x expression
* @param y expression
* @return coalesce expression
*/
@Override
public <Y> Expression<Y> coalesce(@Nonnull final Expression<? extends Y> x,
@Nonnull final Expression<? extends Y> y) {
return new ExpressionImpl.CoalesceExpression<Y>().value(x).value(y);
}
/**
* Create an expression that returns null if all its arguments
* evaluate to null, and the value of the first non-null argument
* otherwise.
* @param x expression
* @param y value
* @return coalesce expression
*/
@Override
public <Y> Expression<Y> coalesce(@Nonnull final Expression<? extends Y> expression, @Nonnull final Y y) {
return new ExpressionImpl.CoalesceExpression<Y>().value(expression).value(literal(y));
}
/**
* Create an expression for string concatenation.
* @param x string expression
* @param second string expression
* @return expression corresponding to concatenation
*/
@Override
public Expression<String> concat(@Nonnull final Expression<String> first, @Nonnull final Expression<String> second) {
return new ExpressionImpl.ConcatExpression(first, second, sqlPattern);
}
/**
* Create an expression for string concatenation.
* @param x string expression
* @param value string
* @return expression corresponding to concatenation
*/
@Override
public Expression<String> concat(@Nonnull final Expression<String> expression, @Nonnull final String value) {
return new ExpressionImpl.ConcatExpression(expression, literal(value), sqlPattern);
}
/**
* Create an expression for string concatenation.
* @param x string
* @param expression string expression
* @return expression corresponding to concatenation
*/
@Override
public Expression<String> concat(@Nonnull final String value, @Nonnull final Expression<String> expression) {
return new ExpressionImpl.ConcatExpression(literal(value), expression, sqlPattern);
}
/**
* Create a conjunction (with zero conjuncts).
* A conjunction with zero conjuncts is true.
* @return and predicate
*/
@Override
public Predicate conjunction() {
throw new NotImplementedException();
}
/**
* Create a selection item corresponding to a constructor.
* This method is used to specify a constructor that will be
* applied to the results of the query execution. If the
* constructor is for an entity class, the resulting entities
* will be in the new state after the query is executed.
* @param resultClass class whose instance is to be constructed
* @param selections arguments to the constructor
* @return compound selection item
* @throws IllegalArgumentException if an argument is a
* tuple- or array-valued selection item
*/
@Override
public <Y> CompoundSelection<Y> construct(@Nonnull final Class<Y> resultClass,
@Nonnull final Selection<?>... selections) {
throw new NotImplementedException();
}
/**
* Create an aggregate expression applying the count operation.
* @param x expression representing input value to count
* operation
* @return count expression
*/
@Override
public Expression<Long> count(@Nonnull final Expression<?> x) {
return new ExpressionImpl.AggregationExpression<>(SqlAggregation.COUNT, x);
}
/**
* Create an aggregate expression applying the count distinct
* operation.
* @param x expression representing input value to count distinct operation
* @return count distinct expression
*/
@Override
public Expression<Long> countDistinct(@Nonnull final Expression<?> x) {
return count(new ExpressionImpl.DistinctExpression<>(x));
}
@Override
public <T> CriteriaDelete<T> createCriteriaDelete(final Class<T> targetEntity) {
throw new NotImplementedException();
}
@Override
public <T> CriteriaUpdate<T> createCriteriaUpdate(final Class<T> targetEntity) {
return new CriteriaUpdateImpl<>(sd, this, parameter, targetEntity, sqlPattern);
}
@Override
public ProcessorCriteriaQuery<Object> createQuery() {
return new CriteriaQueryImpl<>(Object.class, sd, this, sqlPattern);
}
@Override
public <T> ProcessorCriteriaQuery<T> createQuery(final Class<T> resultClass) {
return new CriteriaQueryImpl<>(resultClass, sd, this, sqlPattern);
}
@Override
public ProcessorCriteriaQuery<Tuple> createTupleQuery() {
return new CriteriaQueryImpl<>(Tuple.class, sd, this, sqlPattern);
}
@Override
public Expression<Date> currentDate() {
throw new NotImplementedException();
}
@Override
public Expression<Time> currentTime() {
throw new NotImplementedException();
}
@Override
public Expression<Timestamp> currentTimestamp() {
return new ExpressionImpl.TimeExpression<>(SqlTimeFunctions.TIMESTAMP);
}
/**
* Create an ordering by the descending value of the expression.
* @param x expression used to define the ordering
* @return descending ordering corresponding to the expression
*/
@Override
public Order desc(@Nonnull final Expression<?> x) {
return new OrderImpl(false, Objects.requireNonNull((SqlConvertible) x));
}
/**
* Create an expression that returns the difference
* between its arguments.
* @param x expression
* @param y expression
* @return difference
*/
@Override
public <N extends Number> Expression<N> diff(@Nonnull final Expression<? extends N> x,
@Nonnull final Expression<? extends N> y) {
return new ExpressionImpl.ArithmeticExpression<>(x, y, SqlArithmetic.DIFF);
}
/**
* Create an expression that returns the difference
* between its arguments.
* @param x expression
* @param y value
* @return difference
*/
@Override
public <N extends Number> Expression<N> diff(@Nonnull final Expression<? extends N> x, @Nonnull final N y) {
return new ExpressionImpl.ArithmeticExpression<>(x, literal(y), SqlArithmetic.DIFF);
}
/**
* Create an expression that returns the difference
* between its arguments.
* @param x value
* @param y expression
* @return difference
*/
@Override
public <N extends Number> Expression<N> diff(@Nonnull final N x, @Nonnull final Expression<? extends N> y) {
return new ExpressionImpl.ArithmeticExpression<>(literal(x), y, SqlArithmetic.DIFF);
}
/**
* Create a disjunction (with zero disjuncts).
* A disjunction with zero disjuncts is false.
* @return or predicate
*/
@Override
public Predicate disjunction() {
throw new NotImplementedException();
}
/**
* Create a predicate for testing the arguments for equality.
* @param x expression
* @param y expression
* @return equality predicate
*/
@Override
public Predicate equal(@Nonnull final Expression<?> x, @Nonnull final Expression<?> y) {// NOSONAR
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.EQ);
}
/**
* Create a predicate for testing the arguments for equality.
* @param x expression
* @param y object
* @return equality predicate
*/
@Override
public Predicate equal(@Nonnull final Expression<?> x, final Object y) { // NOSONAR
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.EQ);
}
/**
* Create a predicate testing the existence of a subquery result.
* @param subquery subquery whose result is to be tested
* @return exists predicate
*/
@Override
public Predicate exists(@Nonnull final Subquery<?> subquery) {
return new PredicateImpl.SubQuery(subquery, SqlSubQuery.EXISTS);
}
/**
* Create an expression for the execution of a database
* function.
* @param name function name
* @param type expected result type
* @param args function arguments
* @return expression
*/
@SuppressWarnings("unchecked")
@Override
public <T> Expression<T> function(@Nonnull final String name, @Nonnull final Class<T> type,
final Expression<?>... args) {
final List<Expression<Object>> parameters = args == null ? Collections.emptyList() : Arrays.asList(args).stream()
.map(p -> ((Expression<Object>) p)).toList();
return new ExpressionImpl.FunctionExpression<>(name, type, parameters);
}
/**
* Create a predicate for testing whether the first argument is
* greater than or equal to the second.
* @param x expression
* @param y expression
* @return greater-than-or-equal predicate
*/
@Override
public Predicate ge(@Nonnull final Expression<? extends Number> x, @Nonnull final Expression<? extends Number> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GE);
}
/**
* Create a predicate for testing whether the first argument is
* greater than or equal to the second.
* @param x expression
* @param y expression
* @return greater-than-or-equal predicate
*/
@Override
public Predicate ge(@Nonnull final Expression<? extends Number> x, @Nonnull final Number y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GE);
}
/**
* Create a predicate for testing whether the first argument is
* greater than the second.
* @param x expression
* @param y expression
* @return greater-than predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate greaterThan(@Nonnull final Expression<? extends Y> x,
@Nonnull final Expression<? extends Y> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GT);
}
@Override
public <Y extends Comparable<? super Y>> Predicate greaterThan(@Nonnull final Expression<? extends Y> x,
@Nonnull final Y y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GT);
}
/**
* Create a predicate for testing whether the first argument is
* greater than or equal to the second.
* @param x expression
* @param y expression
* @return greater-than-or-equal predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(@Nonnull final Expression<? extends Y> x,
@Nonnull final Expression<? extends Y> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GE);
}
/**
* Create a predicate for testing whether the first argument is
* greater than or equal to the second.
* @param x expression
* @param y value
* @return greater-than-or-equal predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(@Nonnull final Expression<? extends Y> x,
@Nonnull final Y y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GE);
}
/**
* Create an aggregate expression for finding the greatest of
* the values (strings, dates, etc).
* @param x expression representing input value to greatest
* operation
* @return greatest expression
*/
@Override
public <X extends Comparable<? super X>> Expression<X> greatest(@Nonnull final Expression<X> x) {
throw new NotImplementedException();
}
/**
* Create a predicate for testing whether the first argument is
* greater than the second.
* @param x expression
* @param y expression
* @return greater-than predicate
*/
@Override
public Predicate gt(@Nonnull final Expression<? extends Number> x, @Nonnull final Expression<? extends Number> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GT);
}
/**
* Create a predicate for testing whether the first argument is
* greater than the second.
* @param x expression
* @param y value
* @return greater-than predicate
*/
@Override
public Predicate gt(@Nonnull final Expression<? extends Number> x, @Nonnull final Number y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.GT);
}
/**
* Create predicate to test whether given expression
* is contained in a list of values.
* @param expression to be tested against list of values
* @return in predicate
*/
@Override
public <T> In<T> in(final Expression<? extends T> expression) {
return new PredicateImpl.In<>((Path<? extends T>) expression, parameter);
}
/**
* Create predicate to test whether given expression
* is contained in a list of values.
* @param paths to be tested against list of values
* @return in predicate
*/
@Override
public In<List<Comparable<?>>> in(final List<Path<Comparable<?>>> paths,
final Subquery<List<Comparable<?>>> subquery) {
return new PredicateImpl.In<List<Comparable<?>>>(paths, parameter).value(subquery);
}
/**
* Create predicate to test whether given expression
* is contained in a list of values.
* @param path to be tested against list of values
* @return in predicate
*/
@Override
public <T> In<T> in(final Path<?> path) {
return new PredicateImpl.In<>(path, parameter);
}
/**
* Create a predicate that tests whether a collection is empty.<br>
* Example: "WHERE employee.projects IS EMPTY"
* @param collection expression
* @return is-empty predicate
*/
@Override
public <C extends Collection<?>> Predicate isEmpty(@Nonnull final Expression<C> collection) {
throw new NotImplementedException();
}
/**
* Create a predicate testing for a false value.
* @param x expression to be tested
* @return predicate
*/
@Override
public Predicate isFalse(@Nonnull final Expression<Boolean> x) {
throw new NotImplementedException();
}
/**
* Create a predicate that tests whether an element is
* a member of a collection (property).
* If the collection is empty, the predicate will be false.
* @param elem element expression
* @param collection expression
* @return is-member predicate
*/
@Override
public <E, C extends Collection<E>> Predicate isMember(@Nonnull final E elem,
@Nonnull final Expression<C> collection) {
throw new NotImplementedException();
}
/**
* Create a predicate that tests whether an element is
* a member of a collection (property).
* If the collection is empty, the predicate will be false.
* @param elem element
* @param collection expression
* @return is-member predicate
*/
@Override
public <E, C extends Collection<E>> Predicate isMember(@Nonnull final Expression<E> elem,
@Nonnull final Expression<C> collection) {
throw new NotImplementedException();
}
/**
* Create a predicate that tests whether a collection is not empty.<br>
* Example: WHERE projects.employees IS NOT EMPTY
* @param collection expression
* @return is-not-empty predicate
*/
@Override
public <C extends Collection<?>> Predicate isNotEmpty(@Nonnull final Expression<C> collection) {
throw new NotImplementedException();
}
/**
* Create a predicate that tests whether an element is not a member of a collection.
* If the collection is empty, the predicate will be true.<br>
* Example:
* @param elem element
* @param collection expression
* @return is-not-member predicate
*/
@Override
public <E, C extends Collection<E>> Predicate isNotMember(@Nonnull final E elem,
@Nonnull final Expression<C> collection) {
throw new NotImplementedException();
}
/**
* Create a predicate that tests whether an element is
* not a member of a collection.
* If the collection is empty, the predicate will be true.
* @param elem element expression
* @param collection expression
* @return is-not-member predicate
*/
@Override
public <E, C extends Collection<E>> Predicate isNotMember(@Nonnull final Expression<E> elem,
@Nonnull final Expression<C> collection) {
throw new NotImplementedException();
}
/**
* Create a predicate to test whether the expression is not null.
* @param x expression
* @return is-not-null predicate
*/
@Override
public Predicate isNotNull(@Nonnull final Expression<?> x) {
return new PredicateImpl.NullPredicate(x, SqlNullCheck.NOT_NULL);
}
/**
* Create a predicate to test whether the expression is null.
* @param x expression
* @return is-null predicate
*/
@Override
public Predicate isNull(@Nonnull final Expression<?> x) {
return new PredicateImpl.NullPredicate(x, SqlNullCheck.NULL);
}
/**
* Create a predicate testing for a true value.
* @param x expression to be tested
* @return predicate
*/
@Override
public Predicate isTrue(final Expression<Boolean> x) {
throw new NotImplementedException();
}
/**
* Create an expression that returns the keys of a map.
* @param map map
* @return set expression
*/
@Override
public <K, M extends Map<K, ?>> Expression<Set<K>> keys(@Nonnull final M map) {
throw new NotImplementedException();
}
/**
* Create a predicate for testing whether the first argument is
* less than or equal to the second.
* @param x expression
* @param y expression
* @return less-than-or-equal predicate
*/
@Override
public Predicate le(@Nonnull final Expression<? extends Number> x, @Nonnull final Expression<? extends Number> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LE);
}
/**
* Create a predicate for testing whether the first argument is
* less than or equal to the second.
* @param x expression
* @param y value
* @return less-than-or-equal predicate
*/
@Override
public Predicate le(@Nonnull final Expression<? extends Number> x, @Nonnull final Number y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LE);
}
/**
* Create an aggregate expression for finding the least of
* the values (strings, dates, etc).
* @param x expression representing input value to least
* operation
* @return least expression
*/
@Override
public <X extends Comparable<? super X>> Expression<X> least(@Nonnull final Expression<X> expression) {
throw new NotImplementedException();
}
/**
* Create expression to return length of a string.
* @param x string expression
* @return length expression
*/
@Override
public Expression<Integer> length(@Nonnull final Expression<String> expression) {
return new ExpressionImpl.LengthExpression(expression, sqlPattern);
}
/**
* Create a predicate for testing whether the first argument is
* less than the second.
* @param x expression
* @param y expression
* @return less-than predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate lessThan(@Nonnull final Expression<? extends Y> x,
@Nonnull final Expression<? extends Y> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LT);
}
@Override
public <Y extends Comparable<? super Y>> Predicate lessThan(@Nonnull final Expression<? extends Y> x,
@Nonnull final Y y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LT);
}
/**
* Create a predicate for testing whether the first argument is
* less than or equal to the second.
* @param x expression
* @param y expression
* @return less-than-or-equal predicate
*/
@Override
public <Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(@Nonnull final Expression<? extends Y> x,
@Nonnull final Expression<? extends Y> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LE);
}
@Override
public <Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(@Nonnull final Expression<? extends Y> x,
@Nonnull final Y y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LE);
}
/**
* Create a predicate for testing whether the expression
* satisfies the given pattern.
* @param x string expression
* @param pattern string expression
* @return like predicate
*/
@Override
public Predicate like(@Nonnull final Expression<String> x, @Nonnull final Expression<String> pattern) {
return new PredicateImpl.LikePredicate(Objects.requireNonNull(x),
(ParameterExpression<String, ?>) Objects.requireNonNull(pattern));
}
/**
* Create a predicate for testing whether the expression
* satisfies the given pattern.
* @param x string expression
* @param pattern string expression
* @param escapeChar escape character
* @return like predicate
*/
@Override
public Predicate like(@Nonnull final Expression<String> x, @Nonnull final Expression<String> pattern,
final char escapeChar) {
return like(x, pattern, literal(escapeChar));
}
/**
* Create a predicate for testing whether the expression
* satisfies the given pattern.
* @param x string expression
* @param pattern string expression
* @param escapeChar escape character expression
* @return like predicate
*/
@Override
public Predicate like(@Nonnull final Expression<String> x, @Nonnull final Expression<String> pattern,
final Expression<Character> escapeChar) {
return new PredicateImpl.LikePredicate(Objects.requireNonNull(x),
(ParameterExpression<String, ?>) Objects.requireNonNull(pattern),
Optional.ofNullable((ParameterExpression<Character, ?>) (escapeChar)));
}
/**
* Create a predicate for testing whether the expression
* satisfies the given pattern.
* @param x string expression
* @param pattern string
* @return like predicate
*/
@Override
public Predicate like(@Nonnull final Expression<String> x, @Nonnull final String pattern) {
return like(x, literal(pattern, x));
}
/**
* Create a predicate for testing whether the expression
* satisfies the given pattern.
* @param x string expression
* @param pattern string expression
* @param escapeChar escape character
* @return like predicate
*/
@Override
public Predicate like(@Nonnull final Expression<String> x, @Nonnull final String pattern,
final char escapeChar) {
return like(x, literal(pattern, x), literal(escapeChar));
}
@Override
public Predicate like(final Expression<String> x, final String pattern, final Expression<Character> escapeChar) {
return like(x, literal(pattern, x), escapeChar);
}
/**
* Create an expression for a literal.
* @param value value represented by the expression
* @return expression literal
* @throws IllegalArgumentException if value is null
*/
@Override
public <T> Expression<T> literal(@Nonnull final T value) {
if (value == null) // NOSONAR
throw new IllegalArgumentException("Literal value must not be null");
return parameter.addValue(value);
}
private <T> Expression<T> literal(@Nonnull final T value, @Nonnull final Expression<?> x) {
return parameter.addValue(value, x);
}
/**
* Create expression to locate the position of one string
* within another, returning position of first character
* if found.
* The first position in a string is denoted by 1. If the
* string to be located is not found, 0 is returned.
* @param expression expression for string to be searched
* @param pattern expression for string to be located
* @return expression corresponding to position
*/
@Override
public Expression<Integer> locate(@Nonnull final Expression<String> expression,
@Nonnull final Expression<String> pattern) {
return new ExpressionImpl.LocateExpression(expression, pattern, null, sqlPattern);
}
/**
* Create expression to locate the position of one string
* within another, returning position of first character
* if found.
* The first position in a string is denoted by 1. If the
* string to be located is not found, 0 is returned.
* @param expression expression for string to be searched
* @param pattern expression for string to be located
* @param from expression for position at which to start search
* @return expression corresponding to position
*/
@Override
public Expression<Integer> locate(@Nonnull final Expression<String> expression,
@Nonnull final Expression<String> pattern,
@Nonnull final Expression<Integer> from) {
return new ExpressionImpl.LocateExpression(expression, pattern, from, sqlPattern);
}
/**
* Create expression to locate the position of one string
* within another, returning position of first character
* if found.
* The first position in a string is denoted by 1. If the
* string to be located is not found, 0 is returned.
* @param expression expression for string to be searched
* @param pattern string to be located
* @return expression corresponding to position
*/
@Override
public Expression<Integer> locate(@Nonnull final Expression<String> expression, @Nonnull final String pattern) {
return new ExpressionImpl.LocateExpression(expression, literal(pattern, expression), null, sqlPattern);
}
/**
* Create expression to locate the position of one string
* within another, returning position of first character
* if found.
* The first position in a string is denoted by 1. If the
* string to be located is not found, 0 is returned.
* @param expression expression for string to be searched
* @param pattern string to be located
* @param from position at which to start search
* @return expression corresponding to position
*/
@Override
public Expression<Integer> locate(@Nonnull final Expression<String> expression, @Nonnull final String pattern,
final int from) {
return new ExpressionImpl.LocateExpression(expression, literal(pattern), literal(from), sqlPattern);
}
/**
* Create expression for converting a string to lowercase.
* @param x string expression
* @return expression to convert to lowercase
*/
@Override
public Expression<String> lower(@Nonnull final Expression<String> x) {
return new ExpressionImpl.UnaryFunctionalExpression<>(x, SqlStringFunctions.LOWER);
}
/**
* Create a predicate for testing whether the first argument is
* less than the second.
* @param x expression
* @param y expression
* @return less-than predicate
*/
@Override
public Predicate lt(@Nonnull final Expression<? extends Number> x, @Nonnull final Expression<? extends Number> y) {
return binaryExpression(x, y, PredicateImpl.BinaryExpressionPredicate.Operation.LT);
}
/**
* Create a predicate for testing whether the first argument is
* less than the second.
* @param x expression
* @param y value
* @return less-than predicate
*/
@Override
public Predicate lt(@Nonnull final Expression<? extends Number> x, @Nonnull final Number y) {
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/EntityManagerWrapper.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/EntityManagerWrapper.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.EntityExistsException;
import jakarta.persistence.EntityGraph;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.Query;
import jakarta.persistence.StoredProcedureQuery;
import jakarta.persistence.TransactionRequiredException;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.CriteriaUpdate;
import jakarta.persistence.metamodel.Metamodel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
public class EntityManagerWrapper implements EntityManager { // NOSONAR
private static final Log LOG = LogFactory.getLog(EntityManagerWrapper.class);
private Optional<ProcessorCriteriaBuilder> cb;
private final EntityManager em;
private final JPAServiceDocument sd;
private final ProcessorSqlPatternProvider sqlPattern;
public EntityManagerWrapper(final EntityManager em, final JPAServiceDocument sd,
final ProcessorSqlPatternProvider sqlPattern) {
super();
this.em = em;
this.sd = sd;
this.sqlPattern = sqlPattern != null ? sqlPattern : new SqlDefaultPattern();
this.cb = Optional.empty();
}
/**
* Make an instance managed and persistent.
* @param entity entity instance
* @throws EntityExistsException if the entity already exists.
* (If the entity already exists, the <code>EntityExistsException</code> may
* be thrown when the persist operation is invoked, or the
* <code>EntityExistsException</code> or another <code>PersistenceException</code> may be
* thrown at flush or commit time.)
* @throws IllegalArgumentException if the instance is not an
* entity
* @throws TransactionRequiredException if there is no transaction when
* invoked on a container-managed entity manager of that is of type
* <code>PersistenceContextType.TRANSACTION</code>
*/
@Override
public void persist(final Object entity) {
em.persist(entity);
}
/**
* Merge the state of the given entity into the
* current persistence context.
* @param entity entity instance
* @return the managed instance that the state was merged to
* @throws IllegalArgumentException if instance is not an
* entity or is a removed entity
* @throws TransactionRequiredException if there is no transaction when
* invoked on a container-managed entity manager of that is of type
* <code>PersistenceContextType.TRANSACTION</code>
*/
@Override
public <T> T merge(final T entity) {
return em.merge(entity);
}
/**
* Remove the entity instance.
* @param entity entity instance
* @throws IllegalArgumentException if the instance is not an
* entity or is a detached entity
* @throws TransactionRequiredException if invoked on a
* container-managed entity manager of type
* <code>PersistenceContextType.TRANSACTION</code> and there is
* no transaction
*/
@Override
public void remove(final Object entity) {
em.remove(entity);
}
/**
* Find by primary key.
* Search for an entity of the specified class and primary key.
* If the entity instance is contained in the persistence context,
* it is returned from there.
* @param entityClass entity class
* @param primaryKey primary key
* @return the found entity instance or null if the entity does
* not exist
* @throws IllegalArgumentException if the first argument does
* not denote an entity type or the second argument is
* is not a valid type for that entity's primary key or
* is null
*/
@Override
public <T> T find(final Class<T> entityClass, final Object primaryKey) {
return em.find(entityClass, primaryKey);
}
/**
* Find by primary key, using the specified properties.
* Search for an entity of the specified class and primary key.
* If the entity instance is contained in the persistence
* context, it is returned from there.
* If a vendor-specific property or hint is not recognized,
* it is silently ignored.
* @param entityClass entity class
* @param primaryKey primary key
* @param properties standard and vendor-specific properties
* and hints
* @return the found entity instance or null if the entity does
* not exist
* @throws IllegalArgumentException if the first argument does
* not denote an entity type or the second argument is
* is not a valid type for that entity's primary key or
* is null
* @since Java Persistence 2.0
*/
@Override
public <T> T find(final Class<T> entityClass, final Object primaryKey, final Map<String, Object> properties) {
return em.find(entityClass, primaryKey, properties);
}
@Override
public <T> T find(final Class<T> entityClass, final Object primaryKey, final LockModeType lockMode) {
return em.find(entityClass, primaryKey, lockMode);
}
@Override
public <T> T find(final Class<T> entityClass, final Object primaryKey, final LockModeType lockMode,
final Map<String, Object> properties) {
return em.find(entityClass, primaryKey, lockMode, properties);
}
@Override
public <T> T getReference(final Class<T> entityClass, final Object primaryKey) {
return em.getReference(entityClass, primaryKey);
}
@Override
public void flush() {
em.flush();
}
@Override
public void setFlushMode(final FlushModeType flushMode) {
em.setFlushMode(flushMode);
}
@Override
public FlushModeType getFlushMode() {
return em.getFlushMode();
}
@Override
public void lock(final Object entity, final LockModeType lockMode) {
em.lock(entity, lockMode);
}
@Override
public void lock(final Object entity, final LockModeType lockMode, final Map<String, Object> properties) {
em.lock(entity, lockMode, properties);
}
@Override
public void refresh(final Object entity) {
em.refresh(entity);
}
@Override
public void refresh(final Object entity, final Map<String, Object> properties) {
em.refresh(entity, properties);
}
@Override
public void refresh(final Object entity, final LockModeType lockMode) {
em.refresh(entity, lockMode);
}
@Override
public void refresh(final Object entity, final LockModeType lockMode, final Map<String, Object> properties) {
em.refresh(entity, lockMode, properties);
}
/**
* Clear the persistence context, causing all managed
* entities to become detached. Changes made to entities that
* have not been flushed to the database will not be
* persisted.
*/
@Override
public void clear() {
em.clear();
}
/**
* Remove the given entity from the persistence context, causing
* a managed entity to become detached. Unflushed changes made
* to the entity if any (including removal of the entity),
* will not be synchronized to the database. Entities which
* previously referenced the detached entity will continue to
* reference it.
* @param entity entity instance
* @throws IllegalArgumentException if the instance is not an
* entity
* @since Java Persistence 2.0
*/
@Override
public void detach(final Object entity) {
em.detach(entity);
}
/**
* Check if the instance is a managed entity instance belonging
* to the current persistence context.
* @param entity entity instance
* @return boolean indicating if entity is in persistence context
* @throws IllegalArgumentException if not an entity
*/
@Override
public boolean contains(final Object entity) {
return em.contains(entity);
}
/**
* Get the current lock mode for the entity instance.
* @param entity entity instance
* @return lock mode
* @throws TransactionRequiredException if there is no
* transaction or if the entity manager has not been
* joined to the current transaction
* @throws IllegalArgumentException if the instance is not a
* managed entity and a transaction is active
* @since Java Persistence 2.0
*/
@Override
public LockModeType getLockMode(final Object entity) {
return em.getLockMode(entity);
}
/**
* Set an entity manager property or hint.
* If a vendor-specific property or hint is not recognized, it is
* silently ignored.
* @param propertyName name of property or hint
* @param value value for property or hint
* @throws IllegalArgumentException if the second argument is
* not valid for the implementation
* @since Java Persistence 2.0
*/
@Override
public void setProperty(final String propertyName, final Object value) {
em.setProperty(propertyName, value);
}
/**
* Get the properties and hints and associated values that are in effect
* for the entity manager. Changing the contents of the map does
* not change the configuration in effect.
* @return map of properties and hints in effect for entity manager
* @since Java Persistence 2.0
*/
@Override
public Map<String, Object> getProperties() {
return em.getProperties();
}
/**
* Create an instance of <code>Query</code> for executing a
* Java Persistence query language statement.
* @param queryString a Java Persistence query string
* @return the new query instance
* @throws IllegalArgumentException if the query string is
* found to be invalid
*/
@Override
public Query createQuery(final String queryString) {
return em.createQuery(queryString);
}
/**
* Create an instance of <code>TypedQuery</code> for executing a
* criteria query.
* @param criteriaQuery a criteria query object
* @return the new query instance
* @throws IllegalArgumentException if the criteria query is
* found to be invalid
* @since Java Persistence 2.0
*/
@Override
public <T> TypedQuery<T> createQuery(final CriteriaQuery<T> criteriaQuery) {
final var builder = getCriteriaBuilder();
return new TypedQueryImpl<>(criteriaQuery, this, (ParameterBuffer) builder.getParameterBuffer());
}
/**
* Create an instance of <code>Query</code> for executing a criteria
* update query.
* @param updateQuery a criteria update query object
* @return the new query instance
* @throws IllegalArgumentException if the update query is
* found to be invalid
* @since Java Persistence 2.1
*/
@Override
public Query createQuery(@SuppressWarnings("rawtypes") final CriteriaUpdate updateQuery) {
return em.createQuery(updateQuery);
}
/**
* Create an instance of <code>Query</code> for executing a criteria
* delete query.
* @param deleteQuery a criteria delete query object
* @return the new query instance
* @throws IllegalArgumentException if the delete query is
* found to be invalid
* @since Java Persistence 2.1
*/
@Override
public Query createQuery(@SuppressWarnings("rawtypes") final CriteriaDelete deleteQuery) {
return em.createQuery(deleteQuery);
}
/**
* Create an instance of <code>TypedQuery</code> for executing a
* Java Persistence query language statement.
* The select list of the query must contain only a single
* item, which must be assignable to the type specified by
* the <code>resultClass</code> argument.
* @param queryString a Java Persistence query string
* @param resultClass the type of the query result
* @return the new query instance
* @throws IllegalArgumentException if the query string is found
* to be invalid or if the query result is found to
* not be assignable to the specified type
* @since Java Persistence 2.0
*/
@Override
public <T> TypedQuery<T> createQuery(final String queryString, final Class<T> resultClass) {
throw new NotImplementedException();
}
/**
* Create an instance of <code>Query</code> for executing a named query
* (in the Java Persistence query language or in native SQL).
* @param name the name of a query defined in metadata
* @return the new query instance
* @throws IllegalArgumentException if a query has not been
* defined with the given name or if the query string is
* found to be invalid
*/
@Override
public Query createNamedQuery(final String name) {
LOG.trace("Create query: " + name);
return em.createNamedQuery(name);
}
/**
* Create an instance of <code>TypedQuery</code> for executing a
* Java Persistence query language named query.
* The select list of the query must contain only a single
* item, which must be assignable to the type specified by
* the <code>resultClass</code> argument.
* @param name the name of a query defined in metadata
* @param resultClass the type of the query result
* @return the new query instance
* @throws IllegalArgumentException if a query has not been
* defined with the given name or if the query string is
* found to be invalid or if the query result is found to
* not be assignable to the specified type
* @since Java Persistence 2.0
*/
@Override
public <T> TypedQuery<T> createNamedQuery(final String name, final Class<T> resultClass) {
LOG.trace("Create query: " + name);
return em.createNamedQuery(name, resultClass);
}
/**
* Create an instance of <code>Query</code> for executing
* a native SQL statement, e.g., for update or delete.
* If the query is not an update or delete query, query
* execution will result in each row of the SQL result
* being returned as a result of type Object[] (or a result
* of type Object if there is only one column in the select
* list.) Column values are returned in the order of their
* appearance in the select list and default JDBC type
* mappings are applied.
* @param sqlString a native SQL query string
* @return the new query instance
*/
@Override
public Query createNativeQuery(final String sqlString) {
LOG.trace(sqlString);
return em.createNativeQuery(sqlString);
}
/**
* Create an instance of <code>Query</code> for executing
* a native SQL query.
* @param sqlString a native SQL query string
* @param resultClass the class of the resulting instance(s)
* @return the new query instance
*/
@Override
public Query createNativeQuery(final String sqlString, @SuppressWarnings("rawtypes") final Class resultClass) {
LOG.trace(sqlString);
return em.createNativeQuery(sqlString, resultClass);
}
/**
* Create an instance of <code>Query</code> for executing
* a native SQL query.
* @param sqlString a native SQL query string
* @param resultSetMapping the name of the result set mapping
* @return the new query instance
*/
@Override
public Query createNativeQuery(final String sqlString, final String resultSetMapping) {
throw new NotImplementedException();
}
/**
* Create an instance of <code>StoredProcedureQuery</code> for executing a
* stored procedure in the database.
* <p>
* Parameters must be registered before the stored procedure can
* be executed.
* <p>
* If the stored procedure returns one or more result sets,
* any result set will be returned as a list of type Object[].
* @param name name assigned to the stored procedure query
* in metadata
* @return the new stored procedure query instance
* @throws IllegalArgumentException if a query has not been
* defined with the given name
* @since Java Persistence 2.1
*/
@Override
public StoredProcedureQuery createNamedStoredProcedureQuery(final String name) {
return em.createNamedStoredProcedureQuery(name);
}
/**
* Create an instance of <code>StoredProcedureQuery</code> for executing a
* stored procedure in the database.
* <p>
* Parameters must be registered before the stored procedure can
* be executed.
* <p>
* If the stored procedure returns one or more result sets,
* any result set will be returned as a list of type Object[].
* @param procedureName name of the stored procedure in the
* database
* @return the new stored procedure query instance
* @throws IllegalArgumentException if a stored procedure of the
* given name does not exist (or the query execution will
* fail)
* @since Java Persistence 2.1
*/
@Override
public StoredProcedureQuery createStoredProcedureQuery(final String procedureName) {
return em.createStoredProcedureQuery(procedureName);
}
/**
* Create an instance of <code>StoredProcedureQuery</code> for executing a
* stored procedure in the database.
* <p>
* Parameters must be registered before the stored procedure can
* be executed.
* <p>
* The <code>resultClass</code> arguments must be specified in the order in
* which the result sets will be returned by the stored procedure
* invocation.
* @param procedureName name of the stored procedure in the
* database
* @param resultClasses classes to which the result sets
* produced by the stored procedure are to
* be mapped
* @return the new stored procedure query instance
* @throws IllegalArgumentException if a stored procedure of the
* given name does not exist (or the query execution will
* fail)
* @since Java Persistence 2.1
*/
@Override
public StoredProcedureQuery createStoredProcedureQuery(final String procedureName,
final @SuppressWarnings("rawtypes") Class... resultClasses) {
return em.createStoredProcedureQuery(procedureName, resultClasses);
}
/**
* Create an instance of <code>StoredProcedureQuery</code> for executing a
* stored procedure in the database.
* <p>
* Parameters must be registered before the stored procedure can
* be executed.
* <p>
* The <code>resultSetMapping</code> arguments must be specified in the order
* in which the result sets will be returned by the stored
* procedure invocation.
* @param procedureName name of the stored procedure in the
* database
* @param resultSetMappings the names of the result set mappings
* to be used in mapping result sets
* returned by the stored procedure
* @return the new stored procedure query instance
* @throws IllegalArgumentException if a stored procedure or
* result set mapping of the given name does not exist
* (or the query execution will fail)
*/
@Override
public StoredProcedureQuery createStoredProcedureQuery(final String procedureName,
final String... resultSetMappings) {
return em.createStoredProcedureQuery(procedureName, resultSetMappings);
}
/**
* Indicate to the entity manager that a JTA transaction is
* active and join the persistence context to it.
* <p>
* This method should be called on a JTA application
* managed entity manager that was created outside the scope
* of the active transaction or on an entity manager of type
* <code>SynchronizationType.UNSYNCHRONIZED</code> to associate
* it with the current JTA transaction.
* @throws TransactionRequiredException if there is
* no transaction
*/
@Override
public void joinTransaction() {
em.joinTransaction();
}
/**
* Determine whether the entity manager is joined to the
* current transaction. Returns false if the entity manager
* is not joined to the current transaction or if no
* transaction is active
* @return boolean
* @since Java Persistence 2.1
*/
@Override
public boolean isJoinedToTransaction() {
return em.isJoinedToTransaction();
}
/**
* Return an object of the specified type to allow access to the
* provider-specific API. If the provider's <code>EntityManager</code>
* implementation does not support the specified class, the
* <code>PersistenceException</code> is thrown.
* @param cls the class of the object to be returned. This is
* normally either the underlying <code>EntityManager</code> implementation
* class or an interface that it implements.
* @return an instance of the specified class
* @throws PersistenceException if the provider does not
* support the call
* @since Java Persistence 2.0
*
* @Override
* public <T> T unwrap(final Class<T> cls) {
* return em.unwrap(cls);
* }
*
* /**
* Return the underlying provider object for the <code>EntityManager</code>,
* if available. The result of this method is implementation
* specific.
* <p>
* The <code>unwrap</code> method is to be preferred for new applications.
* @return underlying provider object for EntityManager
*/
@Override
public Object getDelegate() {
return em.getDelegate();
}
/**
* Return an object of the specified type to allow access to the
* provider-specific API. If the provider's <code>EntityManager</code>
* implementation does not support the specified class, the
* <code>PersistenceException</code> is thrown.
* @param clazz the class of the object to be returned. This is
* normally either the underlying <code>EntityManager</code> implementation
* class or an interface that it implements.
* @return an instance of the specified class
* @throws PersistenceException if the provider does not
* support the call
* @since Java Persistence 2.0
*/
@Override
public <T> T unwrap(final Class<T> clazz) {
return em.unwrap(clazz);
}
/**
* Close an application-managed entity manager.
* After the close method has been invoked, all methods
* on the <code>EntityManager</code> instance and any
* <code>Query</code>, <code>TypedQuery</code>, and
* <code>StoredProcedureQuery</code> objects obtained from
* it will throw the <code>IllegalStateException</code>
* except for <code>getProperties</code>,
* <code>getTransaction</code>, and <code>isOpen</code> (which will return false).
* If this method is called when the entity manager is
* joined to an active transaction, the persistence
* context remains managed until the transaction completes.
* @throws IllegalStateException if the entity manager
* is container-managed
*/
@Override
public void close() {
em.close();
}
/**
* Determine whether the entity manager is open.
* @return true until the entity manager has been closed
*/
@Override
public boolean isOpen() {
return em.isOpen();
}
/**
* Return the resource-level <code>EntityTransaction</code> object.
* The <code>EntityTransaction</code> instance may be used serially to
* begin and commit multiple transactions.
* @return EntityTransaction instance
* @throws IllegalStateException if invoked on a JTA
* entity manager
*/
@Override
public EntityTransaction getTransaction() {
return em.getTransaction();
}
/**
* Return the entity manager factory for the entity manager.
* @return EntityManagerFactory instance
* @throws IllegalStateException if the entity manager has
* been closed
* @since Java Persistence 2.0
*/
@Override
public EntityManagerFactory getEntityManagerFactory() {
return em.getEntityManagerFactory();
}
/**
* Return an instance of <code>CriteriaBuilder</code> for the creation of
* <code>CriteriaQuery</code> objects.
* @return CriteriaBuilder instance
* @throws IllegalStateException if the entity manager has
* been closed
* @since Java Persistence 2.0
*/
@Override
public ProcessorCriteriaBuilder getCriteriaBuilder() {
if (!em.isOpen())
throw new IllegalStateException("Entity Manager had been closed");
return cb.orElseGet(() -> {
cb = Optional.of(new CriteriaBuilderImpl(sd, sqlPattern));
return cb.get();
});
}
/**
* Return an instance of <code>Metamodel</code> interface for access to the
* metamodel of the persistence unit.
* @return Metamodel instance
* @throws IllegalStateException if the entity manager has
* been closed
* @since Java Persistence 2.0
*/
@Override
public Metamodel getMetamodel() {
return em.getMetamodel();
}
/**
* Return a mutable EntityGraph that can be used to dynamically create an
* EntityGraph.
* @param rootType class of entity graph
* @return entity graph
* @since Java Persistence 2.1
*/
@Override
public <T> EntityGraph<T> createEntityGraph(final Class<T> rootType) {
return em.createEntityGraph(rootType);
}
/**
* Return a mutable copy of the named EntityGraph. If there
* is no entity graph with the specified name, null is returned.
* @param graphName name of an entity graph
* @return entity graph
* @since Java Persistence 2.1
*/
@Override
public EntityGraph<?> createEntityGraph(final String graphName) {
return em.createEntityGraph(graphName);
}
/**
* Return a named EntityGraph. The returned EntityGraph
* should be considered immutable.
* @param graphName name of an existing entity graph
* @return named entity graph
* @throws IllegalArgumentException if there is no EntityGraph of
* the given name
* @since Java Persistence 2.1
*/
@Override
public EntityGraph<?> getEntityGraph(final String graphName) {
return em.getEntityGraph(graphName);
}
/**
* Return all named EntityGraphs that have been defined for the provided
* class type.
* @param entityClass entity class
* @return list of all entity graphs defined for the entity
* @throws IllegalArgumentException if the class is not an entity
* @since Java Persistence 2.1
*/
@Override
public <T> List<EntityGraph<? super T>> getEntityGraphs(final Class<T> entityClass) {
return em.getEntityGraphs(entityClass);
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CompoundPathImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/CompoundPathImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.List;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
final record CompoundPathImpl(@Nonnull List<Path<Comparable<?>>> paths) implements CompoundPath {
public static final String OPENING_BRACKET = "(";
public static final String CLOSING_BRACKET = ")";
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(OPENING_BRACKET);
statement.append(paths
.stream()
.map(path -> ((Expression<?>) path)) // NOSONAR
.collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
statement.append(CLOSING_BRACKET);
return statement;
}
@Override
public boolean isEmpty() {
return paths.isEmpty();
}
@Override
public Path<?> getFirst() throws IllegalStateException {
if (isEmpty())
throw new IllegalStateException();
return paths.get(0);
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/AbstractQueryImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/AbstractQueryImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.LockModeType;
import jakarta.persistence.Parameter;
import jakarta.persistence.Query;
import jakarta.persistence.TemporalType;
import com.sap.olingo.jpa.processor.cb.impl.ExpressionImpl.ParameterExpression;
abstract class AbstractQueryImpl implements Query {
static final String SET_A_PARAMETER_EXCEPTION =
"Set a parameter is not supported. Parameter have to be forwarded from criteria query";
private final ParameterBuffer parameterBuffer;
private Optional<LockModeType> lockMode;
private final Map<String, Object> hints;
private Optional<FlushModeType> flushMode;
AbstractQueryImpl(final ParameterBuffer parameterBuffer) {
super();
this.parameterBuffer = parameterBuffer;
this.hints = new HashMap<>();
this.lockMode = Optional.empty();
this.flushMode = Optional.empty();
}
@CheckForNull
@Override
public LockModeType getLockMode() {
return lockMode.orElse(null);
}
@Override
public Query setLockMode(final LockModeType lockMode) {
this.lockMode = Optional.ofNullable(lockMode);
return this;
}
@CheckForNull
@Override
public FlushModeType getFlushMode() {
return flushMode.orElse(null);
}
@Override
public Query setFlushMode(final FlushModeType flushMode) {
this.flushMode = Optional.ofNullable(flushMode);
return this;
}
@Override
public Map<String, Object> getHints() {
return this.hints;
}
@Override
public Query setHint(final String hintName, final Object value) {
this.hints.put(hintName, value);
return this;
}
/**
* Return a boolean indicating whether a value has been bound
* to the parameter.
* @param param parameter object
* @return boolean indicating whether parameter has been bound
* @since 2.0
*/
@Override
public boolean isBound(final Parameter<?> param) {
return parameterBuffer.getParameters().containsValue(param);
}
/**
* Get the parameter object corresponding to the declared
* positional parameter with the given position.
* This method is not required to be supported for native
* queries.
* @param position position
* @return parameter object
* @throws IllegalArgumentException if the parameter with the
* specified position does not exist
* @throws IllegalStateException if invoked on a native
* query when the implementation does not support
* this use
* @since 2.0
*/
@Override
public Parameter<?> getParameter(final int position) {
final Optional<?> parameter = parameterBuffer
.getParameters()
.values()
.stream()
.filter(p -> p.getPosition().equals(position))
.findFirst();
return (Parameter<?>) parameter
.orElseThrow(() -> new IllegalArgumentException("No parameter with index " + position));
}
/**
* Get the parameter object corresponding to the declared
* positional parameter with the given position and type.
* This method is not required to be supported by the provider.
* @param position position
* @param type type
* @return parameter object
* @throws IllegalArgumentException if the parameter with the
* specified position does not exist or is not assignable
* to the type
* @throws IllegalStateException if invoked on a native
* query or Jakarta Persistence query language query when
* the implementation does not support this use
* @since 2.0
*/
@SuppressWarnings("unchecked")
@Override
public <X> Parameter<X> getParameter(final int position, final Class<X> type) {
final var parameter = getParameter(position);
if (parameter.getParameterType() != null && type != null && !type.isAssignableFrom(parameter.getParameterType()))
throw new IllegalArgumentException("Parameter at " + position + " has different type");
return (Parameter<X>) parameter;
}
/**
* Get the parameter object corresponding to the declared
* parameter of the given name.
* This method is not required to be supported for native
* queries.
* @param name parameter name
* @return parameter object
* @throws IllegalArgumentException if the parameter of the
* specified name does not exist
* @throws IllegalStateException if invoked on a native
* query when the implementation does not support
* this use
* @since 2.0
*/
@Override
public Parameter<?> getParameter(final String name) {
final var position = Integer.valueOf(name);
return getParameter(position);
}
/**
* Get the parameter object corresponding to the declared
* parameter of the given name and type.
* This method is required to be supported for criteria queries
* only.
* @param name parameter name
* @param type type
* @return parameter object
* @throws IllegalArgumentException if the parameter of the
* specified name does not exist or is not assignable
* to the type
* @throws IllegalStateException if invoked on a native
* query or Jakarta Persistence query language query when
* the implementation does not support this use
* @since 2.0
*/
@SuppressWarnings("unchecked")
@Override
public <X> Parameter<X> getParameter(final String name, final Class<X> type) {
final var parameter = getParameter(name);
if (parameter.getParameterType() != null && type != null && !type.isAssignableFrom(parameter.getParameterType()))
throw new IllegalArgumentException("Parameter with name " + name + " has different type");
return (Parameter<X>) parameter;
}
/**
* Get the parameter objects corresponding to the declared
* parameters of the query.
* Returns empty set if the query has no parameters.
* This method is not required to be supported for native
* queries.
* @return set of the parameter objects
* @throws IllegalStateException if invoked on a native
* query when the implementation does not support
* this use
* @since 2.0
*/
@Override
public Set<Parameter<?>> getParameters() {
return parameterBuffer.getParameters()
.values().stream().collect(Collectors.toSet());
}
/**
* Return the input value bound to the positional parameter.
* (Note that OUT parameters are unbound.)
* @param position position
* @return parameter value
* @throws IllegalStateException if the parameter has not been
* been bound
* @throws IllegalArgumentException if the parameter with the
* specified position does not exist
* @since 2.0
*/
@Override
public Object getParameterValue(final int position) {
final Optional<?> parameter = parameterBuffer
.getParameters()
.values()
.stream()
.filter(p -> p.getPosition().equals(position))
.findFirst();
return parameter.orElseThrow(() -> new IllegalArgumentException("No parameter with index " + position));
}
/**
* Return the input value bound to the parameter.
* (Note that OUT parameters are unbound.)
* @param param parameter object
* @return parameter value
* @throws IllegalArgumentException if the parameter is not
* a parameter of the query
* @throws IllegalStateException if the parameter has not been
* been bound
* @since 2.0
*/
@SuppressWarnings("unchecked")
@Override
public <X> X getParameterValue(final Parameter<X> param) {
final Optional<ParameterExpression<Object, Object>> parameter = parameterBuffer.getParameters().values()
.stream()
.filter(p -> p.equals(param))
.findFirst();
return (X) parameter.map(ParameterExpression::getValue)
.orElseThrow(() -> new IllegalArgumentException("Parameter unknown " + param));
}
@Override
public Object getParameterValue(final String name) {
final ParameterExpression<?, ?> parameter = (ParameterExpression<?, ?>) getParameter(name);
return parameter.getValue();
}
@Override
public Query setParameter(final int position, final Calendar value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final int position, final Date value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final int position, final Object value) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final Parameter<Calendar> param, final Calendar value,
final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final Parameter<Date> param, final Date value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public <X> Query setParameter(final Parameter<X> param, final X value) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final String name, final Calendar value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final String name, final Date value, final TemporalType temporalType) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
@Override
public Query setParameter(final String name, final Object value) {
throw new IllegalStateException(SET_A_PARAMETER_EXCEPTION);
}
void copyParameter(final Query query) {
parameterBuffer.getParameters().entrySet().stream().forEach(entry -> query.setParameter(entry.getValue()
.getPosition(), entry.getValue().getValue()));
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TupleImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TupleImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import static com.sap.olingo.jpa.processor.cb.impl.TypeConverter.convert;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import jakarta.persistence.Tuple;
import jakarta.persistence.TupleElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
/**
*
* @author Oliver Grande
* @since 1.0.0
*/
class TupleImpl implements Tuple {
private final Object[] values;
private final List<Entry<String, JPAAttribute>> selection;
private final Map<String, Integer> selectionIndex;
private Optional<List<TupleElement<?>>> tupleElements;
TupleImpl(final Object value, final List<Entry<String, JPAAttribute>> selection,
final Map<String, Integer> selectionIndex) {
this(new Object[] { value }, selection, selectionIndex);
}
TupleImpl(final Object[] values, final List<Entry<String, JPAAttribute>> selection,
final Map<String, Integer> selectionIndex) {
super();
this.values = values;
this.selection = selection;
this.selectionIndex = selectionIndex;
this.tupleElements = Optional.empty();
}
/**
* Get the value of the element at the specified
* position in the result tuple. The first position is 0.
* <p>
* <b>Please note:</b> As of now <b>no</b> conversions are made.
* @param i position in result tuple
* @return value of the tuple element
* @throws IllegalArgumentException if i exceeds
* length of result tuple
*/
@Override
public Object get(final int index) {
if (index >= values.length || index < 0)
throw new IllegalArgumentException("Index out of bound");
return values[index];
}
/**
* Get the value of the element at the specified
* position in the result tuple. The first position is 0.
* <p>
* <b>Please note:</b> As of now <b>no</b> conversions are made.
* @param i position in result tuple
* @param type type of the tuple element
* @return value of the tuple element
* @throws IllegalArgumentException if i exceeds
* length of result tuple or element cannot be
* assigned to the specified type
*/
@SuppressWarnings("unchecked")
@Override
public <X> X get(final int i, final Class<X> type) {
return (X) convert(get(i), type);
}
/**
* Get the value of the tuple element to which the
* specified alias has been assigned.
* @param alias alias assigned to tuple element
* @return value of the tuple element
* @throws IllegalArgumentException if alias
* does not correspond to an element in the
* query result tuple
*/
@Override
public Object get(final String alias) {
if (selectionIndex.containsKey(alias)) {
final int index = selectionIndex.get(alias);
final JPAAttribute attribute = selection.get(index).getValue();
if (values[index] == null)
return null;
final Object value = convert(values[index], attribute.getDbType());
if (attribute.isEnum() && attribute.getConverter() == null) {
if (value instanceof String) {
for (final var enumValue : attribute.getType().getEnumConstants()) {
if (enumValue.toString().equals(value))
return enumValue;
}
} else if (value instanceof final Integer ordinal) {
return attribute.getType().getEnumConstants()[ordinal];
} else {
throw new IllegalArgumentException("Unsupported tagets type: " + attribute.getDbType());
}
}
if (attribute.getRawConverter() != null)
return attribute.getRawConverter().convertToEntityAttribute(value);
return value;
} else {
throw new IllegalArgumentException("Unknown alias: " + alias);
}
}
/**
* Get the value of the tuple element to which the
* specified alias has been assigned.
* @param alias alias assigned to tuple element
* @param type of the tuple element
* @return value of the tuple element
* @throws IllegalArgumentException if alias
* does not correspond to an element in the
* query result tuple or element cannot be
* assigned to the specified type
*/
@SuppressWarnings("unchecked")
@Override
public <X> X get(final String alias, final Class<X> type) {
return (X) convert(get(alias), type);
}
/**
* Get the value of the specified tuple element.
* @param tupleElement tuple element
* @return value of tuple element
* @throws IllegalArgumentException if tuple element
* does not correspond to an element in the
* query result tuple
*/
@Override
public <X> X get(final TupleElement<X> tupleElement) {
return get(tupleElement.getAlias(), tupleElement.getJavaType());
}
/**
* Return the tuple elements.
* @return tuple elements
*/
@Override
public List<TupleElement<?>> getElements() {
return tupleElements.orElseGet(this::asTupleElements);
}
/**
* Return the values of the result tuple elements as an array.
* @return tuple element values
*/
@Override
public Object[] toArray() {
return Arrays.copyOf(values, values.length);
}
private List<TupleElement<?>> asTupleElements() {
tupleElements = Optional.of(
selectionIndex.entrySet()
.stream()
.map(element -> new TupleElementImpl<>(element.getValue()))
.collect(Collectors.toList())); // NOSONAR
return tupleElements.orElseThrow(IllegalStateException::new);
}
private class TupleElementImpl<X> implements TupleElement<X> {
private final int index;
private TupleElementImpl(final int index) {
super();
this.index = index;
}
@Override
public String getAlias() {
return selection.get(index).getKey();
}
@SuppressWarnings("unchecked")
@Override
public Class<? extends X> getJavaType() {
return (Class<? extends X>) selection.get(index).getValue().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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/JPAAttributeWrapper.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/JPAAttributeWrapper.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.lang.reflect.Constructor;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.criteria.Selection;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmItem;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmTransientPropertyCalculator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class JPAAttributeWrapper implements JPAAttribute {
private final Selection<?> selection;
public JPAAttributeWrapper(final Selection<?> selection) {
this.selection = selection;
}
@Override
public FullQualifiedName getExternalFQN() {
return null;
}
@Override
public String getExternalName() {
return null;
}
@Override
public String getInternalName() {
return null;
}
@Override
public <X, Y> AttributeConverter<X, Y> getConverter() {
return null;
}
@Override
public <X, Y> AttributeConverter<X, Y> getRawConverter() {
return null;
}
@Override
public EdmPrimitiveTypeKind getEdmType() throws ODataJPAModelException {
return null;
}
@Override
public CsdlAbstractEdmItem getProperty() throws ODataJPAModelException {
return null;
}
@Override
public JPAStructuredType getStructuredType() throws ODataJPAModelException {
return null;
}
@Override
public Set<String> getProtectionClaimNames() {
return Collections.emptySet();
}
@Override
public List<String> getProtectionPath(final String claimName) throws ODataJPAModelException {
return Collections.emptyList();
}
@Override
public Class<?> getType() {
return selection.getJavaType();
}
@Override
public Class<?> getDbType() {
return selection.getJavaType();
}
@Override
public boolean isAssociation() {
return false;
}
@Override
public boolean isCollection() {
return false;
}
@Override
public boolean hasProtection() {
return false;
}
@Override
public boolean isTransient() {
return false;
}
@Override
public <T extends EdmTransientPropertyCalculator<?>> Constructor<T> getCalculatorConstructor() {
return null;
}
@Override
public List<String> getRequiredProperties() {
return Collections.emptyList();
}
@Override
public Class<?> getJavaType() {
return null;
}
@Override
public CsdlAnnotation getAnnotation(final String alias, final String term) throws ODataJPAModelException {
return null;
}
@Override
public Object getAnnotationValue(final String alias, final String term, final String property)
throws ODataJPAModelException {
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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SelectionPath.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SelectionPath.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.metamodel.Bindable;
import jakarta.persistence.metamodel.MapAttribute;
import jakarta.persistence.metamodel.PluralAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
/**
*
* @author Oliver Grande
* @since 1.0.1
* @created 29.12.2020
* @param <X>
*/
class SelectionPath<X> extends ExpressionImpl<X> implements Path<X> {
final SqlSelection<X> selection;
final Optional<String> tableAlias;
SelectionPath(@Nonnull final SqlSelection<X> selection, @Nonnull final Optional<String> tableAlias) {
this.selection = selection;
this.tableAlias = tableAlias;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
tableAlias.ifPresent(alias -> {
statement.append(alias);
statement.append(DOT);
});
return statement.append(selection.getAlias().replaceAll(SELECTION_REPLACEMENT_REGEX, SELECTION_REPLACEMENT));
}
@Override
public <Y> Path<Y> get(final SingularAttribute<? super X, Y> attribute) {
throw new NotImplementedException();
}
@Override
public <E, C extends Collection<E>> Expression<C> get(final PluralAttribute<X, C, E> attribute) {
throw new NotImplementedException();
}
@Override
public <K, V, M extends Map<K, V>> Expression<M> get(final MapAttribute<X, K, V> attribute) {
throw new NotImplementedException();
}
@Override
public <Y> Path<Y> get(final String attribute) {
throw new NotImplementedException();
}
@Override
public Bindable<X> getModel() {
throw new NotImplementedException();
}
@Override
public Path<?> getParentPath() {
throw new NotImplementedException();
}
@Override
public Expression<Class<? extends X>> type() {
throw new NotImplementedException();
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlDefaultPattern.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SqlDefaultPattern.java | package com.sap.olingo.jpa.processor.cb.impl;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
class SqlDefaultPattern implements ProcessorSqlPatternProvider {
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/FromImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/FromImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nonnull;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.InheritanceType;
import jakarta.persistence.criteria.CollectionJoin;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Fetch;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.ListJoin;
import jakarta.persistence.criteria.MapJoin;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.SetJoin;
import jakarta.persistence.metamodel.CollectionAttribute;
import jakarta.persistence.metamodel.ListAttribute;
import jakarta.persistence.metamodel.MapAttribute;
import jakarta.persistence.metamodel.PluralAttribute;
import jakarta.persistence.metamodel.SetAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAInheritanceType;
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.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
/**
* Represents a bound type, usually an entity that appears in
* the from clause, but may also be an embeddable belonging to
* an entity in the from clause.
* <p>
* Serves as a factory for Joins of associations, embeddables, and
* collections belonging to the type, and for Paths of attributes
* belonging to the type.
*
* @param <Z> the source type
* @param <X> the target type
*
* @since Java Persistence 2.0
*/
@SuppressWarnings("hiding")
class FromImpl<Z, X> extends PathImpl<X> implements From<Z, X> {
private static final Log LOGGER = LogFactory.getLog(FromImpl.class);
private final Set<Join<X, ?>> joins;
private final Set<Fetch<X, ?>> fetches;
private final AliasBuilder aliasBuilder;
private InheritanceInfo inInfo;
private final CriteriaBuilder cb;
Optional<? extends AbstractJoinImp<X, ?>> inheritanceJoin;
FromImpl(final JPAEntityType type, final AliasBuilder aliasBuilder, final CriteriaBuilder cb) {
this(type, null, aliasBuilder, cb);
}
FromImpl(final JPAEntityType type, final JPAPath path, final AliasBuilder aliasBuilder, final CriteriaBuilder cb) {
super(Optional.ofNullable(path), Optional.empty(), type, Optional.of(aliasBuilder.getNext()));
this.joins = new HashSet<>();
this.fetches = new HashSet<>();
this.aliasBuilder = aliasBuilder;
this.cb = cb;
this.inInfo = new InheritanceInfo(type);
this.inheritanceJoin = addInheritanceJoin();
this.inheritanceJoin.ifPresent(joins::add);
}
private Optional<InheritanceJoin<X, ?>> addInheritanceJoin() {
var strategy = inInfo.getInheritanceType();
try {
if (st != null
&& strategy.isPresent()
&& strategy.get() == InheritanceType.JOINED
&& st.getBaseType() != null) {
return Optional.of(new InheritanceJoin<>(st, this, aliasBuilder, cb));
}
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
return Optional.empty();
}
private Optional<InheritanceJoinReversed<X, ?>> addReverseInheritanceJoin(JPAEntityType target) {
try {
if (st != null
&& target.getInheritanceInformation().getInheritanceType() == JPAInheritanceType.JOIN_TABLE
&& target.getBaseType() != null) {
return Optional.of(new InheritanceJoinReversed<>(target, st, this, aliasBuilder, cb));
}
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
return Optional.empty();
}
/**
* Perform a type cast upon the expression, returning a new expression object.
* This method does not cause type conversion:<br>
* the runtime type is not changed.
* Warning: may result in a runtime failure.
* @param type intended type of the expression
* @return new expression of the given type
*/
@SuppressWarnings("unchecked")
@Override
public <X> Expression<X> as(final Class<X> type) {
try {
final JPAEntityType target = ((CriteriaBuilderImpl) cb).getServiceDocument().getEntity(type);
if (target == null)
throw new IllegalArgumentException(type.getName() + " is unknown");
if (isSubtype(type)) {
if (target.getInheritanceInformation().getInheritanceType() == JPAInheritanceType.JOIN_TABLE) {
inheritanceJoin = addReverseInheritanceJoin(target);
inheritanceJoin.ifPresent(joins::add);
return (Expression<X>) inheritanceJoin.map(join -> (InheritanceJoinReversed<?, ?>) join)
.map(InheritanceJoinReversed::getTarget).orElse((From<Object, Object>) this);
} else {
st = target;
inInfo = new InheritanceInfo(target);
}
}
return (Expression<X>) this;
} catch (final ODataJPAModelException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(st.getTableName());
tableAlias.ifPresent(alias -> statement.append(" ").append(alias));
statement.append(joins.stream().collect(new StringBuilderCollector.ExpressionCollector(statement, " ")));
return statement;
}
/**
* Create a fetch join to the specified collection-valued
* attribute using an inner join.
* @param attribute target of the join
* @return the resulting join
*/
@Override
public <Y> Fetch<X, Y> fetch(@Nonnull final PluralAttribute<? super X, ?, Y> attribute) {
throw new NotImplementedException();
}
/**
* Create a fetch join to the specified collection-valued
* attribute using the given join type.
* @param attribute target of the join
* @param joinType join type
* @return the resulting join
*/
@Override
public <Y> Fetch<X, Y> fetch(@Nonnull final PluralAttribute<? super X, ?, Y> attribute,
@Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create a fetch join to the specified single-valued attribute
* using an inner join.
* @param attribute target of the join
* @return the resulting fetch join
*/
@Override
public <Y> Fetch<X, Y> fetch(@Nonnull final SingularAttribute<? super X, Y> attribute) {
throw new NotImplementedException();
}
/**
* Create a fetch join to the specified single-valued attribute
* using the given join type.
* @param attribute target of the join
* @param joinType join type
* @return the resulting fetch join
*/
@Override
public <Y> Fetch<X, Y> fetch(@Nonnull final SingularAttribute<? super X, Y> attribute,
@Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create a fetch join to the specified attribute using an
* inner join.
* @param attributeName name of the attribute for the
* target of the join
* @return the resulting fetch join
* @throws IllegalArgumentException if attribute of the given
* name does not exist
*/
@Override
public <X, Y> Fetch<X, Y> fetch(@Nonnull final String attributeName) {
throw new NotImplementedException();
}
/**
* Create a fetch join to the specified attribute using
* the given join type.
* @param attributeName name of the attribute for the
* target of the join
* @param joinType join type
* @return the resulting fetch join
* @throws IllegalArgumentException if attribute of the given
* name does not exist
*/
@Override
public <X, Y> Fetch<X, Y> fetch(@Nonnull final String attributeName, @Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Returns the parent <code>From</code> object from which the correlated
* <code>From</code> object has been obtained through correlation (use
* of a <code>Subquery</code> <code>correlate</code> method).
* @return the parent of the correlated From object
* @throws IllegalStateException if the From object has
* not been obtained through correlation
*/
@Override
public From<Z, X> getCorrelationParent() {
throw new NotImplementedException();
}
/**
* Return the fetch joins that have been made from this type.
* Returns empty set if no fetch joins have been made from
* this type.
* Modifications to the set do not affect the query.
* @return fetch joins made from this type
*/
@Override
public Set<Fetch<X, ?>> getFetches() {
return fetches;
}
@SuppressWarnings("unchecked")
@Override
public Class<? extends X> getJavaType() {
return (Class<? extends X>) st.getTypeClass();
}
/**
* Return the joins that have been made from this bound type.
* Returns empty set if no joins have been made from this
* bound type.
* Modifications to the set do not affect the query.
* @return joins made from this type
*/
@Override
public Set<Join<X, ?>> getJoins() {
return joins;
}
/**
* Whether the <code>From</code> object has been obtained as a result of
* correlation (use of a <code>Subquery</code> <code>correlate</code>
* method).
* @return boolean indicating whether the object has been
* obtained through correlation
*/
@Override
public boolean isCorrelated() {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Collection-valued
* attribute.
* @param collection target of the join
* @return the resulting join
*/
@Override
public <Y> CollectionJoin<X, Y> join(@Nonnull final CollectionAttribute<? super X, Y> collection) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Collection-valued
* attribute.
* @param collection target of the join
* @return the resulting join
*/
@Override
public <Y> CollectionJoin<X, Y> join(@Nonnull final CollectionAttribute<? super X, Y> collection,
@Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified List-valued attribute.
* @param list target of the join
* @return the resulting join
*/
@Override
public <Y> ListJoin<X, Y> join(@Nonnull final ListAttribute<? super X, Y> list) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified List-valued attribute.
* @param list target of the join
* @return the resulting join
*/
@Override
public <Y> ListJoin<X, Y> join(@Nonnull final ListAttribute<? super X, Y> list, @Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Map-valued attribute.
* @param map target of the join
* @return the resulting join
*/
@Override
public <K, V> MapJoin<X, K, V> join(@Nonnull final MapAttribute<? super X, K, V> map) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Map-valued attribute.
* @param map target of the join
* @return the resulting join
*/
@Override
public <K, V> MapJoin<X, K, V> join(@Nonnull final MapAttribute<? super X, K, V> map,
@Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Set-valued attribute.
* @param set target of the join
* @return the resulting join
*/
@Override
public <Y> SetJoin<X, Y> join(@Nonnull final SetAttribute<? super X, Y> set) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Set-valued attribute.
* @param set target of the join
* @return the resulting join
*/
@Override
public <Y> SetJoin<X, Y> join(@Nonnull final SetAttribute<? super X, Y> set, @Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified single-valued attribute.
* @param attribute target of the join
* @return the resulting join
*/
@Override
public <Y> Join<X, Y> join(@Nonnull final SingularAttribute<? super X, Y> attribute) {
throw new NotImplementedException();
}
/**
* Create a join to the specified single-valued attribute
* using the given join type.
* @param attribute target of the join
* @param joinType join type
* @return the resulting join
*/
@Override
public <Y> Join<X, Y> join(@Nonnull final SingularAttribute<? super X, Y> attribute, final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified attribute.
* @param attributeName name of the attribute for the
* target of the join
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given
* name does not exist
*/
@Override
public <X, Y> Join<X, Y> join(@Nonnull final String attributeName) {
return join(attributeName, null);
}
/**
* Create a join to the specified attribute using the given join type.
* @param attributeName name of the attribute for the target of the join
* @param joinType join type
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given name does not exist
*/
@SuppressWarnings("unchecked")
@Override
public <X, Y> Join<X, Y> join(@Nonnull final String attributeName, final JoinType jt) {
try {
final JPAStructuredType source = determineSource();
final JPAAttribute joinAttribute = source
.getAttribute(Objects.requireNonNull(attributeName))
.orElseGet(() -> getAssociation(source, attributeName));
if (joinAttribute == null)
throw new IllegalArgumentException(buildExceptionText(attributeName));
@SuppressWarnings("rawtypes")
Join join;
if (joinAttribute instanceof final JPADescriptionAttribute attribute) {
final JoinType joinType = jt == null ? JoinType.LEFT : jt;
final Optional<JPAAssociationPath> path = Optional.ofNullable(attribute.asAssociationAttribute().getPath());
join = new SimpleJoin<>(path.orElseThrow(() -> new IllegalArgumentException(buildExceptionText(
attributeName))),
joinType, determineParent(), aliasBuilder, cb);
} else if (joinAttribute instanceof JPACollectionAttribute) {
join = new CollectionJoinImpl<>(getJPAPath(joinAttribute), determineParent(), aliasBuilder, cb, jt);
} else if (joinAttribute.isComplex()) {
join = new PathJoin<>((FromImpl<X, Y>) determineParent(), getJPAPath(joinAttribute), aliasBuilder, cb);
} else {
final JoinType joinType = jt == null ? JoinType.INNER : jt;
Optional<JPAAssociationPath> associationPath;
if (path.isPresent())
associationPath = Optional.ofNullable(st.getAssociationPath(path.get().getAlias() + JPAPath.PATH_SEPARATOR
+ joinAttribute.getExternalName()));
else
associationPath = Optional.ofNullable(source.getAssociationPath(joinAttribute.getExternalName()));
if (associationPath.orElseThrow(() -> new IllegalArgumentException(buildExceptionText(attributeName)))
.hasJoinTable())
join = new JoinTableJoin<>(associationPath.orElseThrow(() -> new IllegalArgumentException(
buildExceptionText(
attributeName))), joinType, determineParent(), aliasBuilder, cb);
else
join = new SimpleJoin<>(associationPath.orElseThrow(() -> new IllegalArgumentException(buildExceptionText(
attributeName))), joinType, determineParent(), aliasBuilder, cb);
}
joins.add(join);
return join;
} catch (ODataJPAModelException | IllegalArgumentException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Create an inner join to the specified Collection-valued attribute.
* @param attributeName name of the attribute for the target of the join
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given name does not exist
*/
@Override
public <X, Y> CollectionJoin<X, Y> joinCollection(@Nonnull final String attributeName) {
throw new NotImplementedException();
}
/**
* Create a join to the specified Collection-valued attribute using the given join type.
* @param attributeName name of the attribute for the target of the join
* @param joinType join type
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given name does not exist
*/
@Override
public <X, Y> CollectionJoin<X, Y> joinCollection(@Nonnull final String attributeName,
@Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified List-valued attribute.
* @param attributeName name of the attribute for the
* target of the join
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given
* name does not exist
*/
@Override
public <X, Y> ListJoin<X, Y> joinList(@Nonnull final String attributeName) {
throw new NotImplementedException();
}
/**
* Create a join to the specified List-valued attribute using the given join type.
* @param attributeName name of the attribute for the target of the join
* @param joinType join type
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given name does not exist
*/
@Override
public <X, Y> ListJoin<X, Y> joinList(@Nonnull final String attributeName, @Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Map-valued attribute.
* @param attributeName name of the attribute for the
* target of the join
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given
* name does not exist
*/
@Override
public <X, K, V> MapJoin<X, K, V> joinMap(@Nonnull final String attributeName) {
throw new NotImplementedException();
}
/**
* Create a join to the specified Map-valued attribute using the given join type.
* @param attributeName name of the attribute for the target of the join
* @param joinType join type
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given name does not exist
*/
@Override
public <X, K, V> MapJoin<X, K, V> joinMap(@Nonnull final String attributeName, @Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
/**
* Create an inner join to the specified Set-valued attribute.
* @param attributeName name of the attribute for the
* target of the join
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given
* name does not exist
*/
@Override
public <X, Y> SetJoin<X, Y> joinSet(@Nonnull final String attributeName) {
throw new NotImplementedException();
}
/**
* Create a join to the specified Set-valued attribute using the given join type.
* @param attributeName name of the attribute for the target of the join
* @param joinType join type
* @return the resulting join
* @throws IllegalArgumentException if attribute of the given name does not exist
*/
@Override
public <X, Y> SetJoin<X, Y> joinSet(@Nonnull final String attributeName, @Nonnull final JoinType joinType) {
throw new NotImplementedException();
}
String buildExceptionText(final String attributeName) {
return "'&a' is unknown at '&e'".replace("&a",
attributeName).replace("&e", st.getInternalName());
}
Expression<Boolean> createInheritanceWhere() {
if (inInfo.getInheritanceType().filter(type -> type == InheritanceType.SINGLE_TABLE).isPresent()) {
return createInheritanceWhereSingleTable();
} else if (inInfo.getInheritanceType().filter(type -> type == InheritanceType.JOINED).isPresent()) {
return createInheritanceWhereJoined();
}
return null;
}
private final Expression<Boolean> createInheritanceWhereJoined() {
// attribute from base, value from leave
final Optional<String> columnName = inInfo.getDiscriminatorColumn();
// if (!columnName.isPresent()) {
// LOGGER.warn("Now discriminator column found at " + inInfo.getBaseClass().map(Class::getCanonicalName).orElse(
// "?"));
// } else {
// if (!(this instanceof AbstractJoinImp)) {
// var root = getInheritanceRoot();
// final List<JPAPath> pathList = getInheritanceRootPathList(root);
// final Path<?> columnPath = getDiscriminatorColumn(columnName, root, pathList);
// final DiscriminatorValue value = st.getTypeClass().getDeclaredAnnotation(DiscriminatorValue.class);
// if (value == null || columnPath == null)
// throw new IllegalStateException("DiscriminatorValue annotation missing at " + st.getTypeClass()
// .getCanonicalName());
// return cb.equal(columnPath, value.value());
// }
// }
if (columnName.isPresent()) {
LOGGER.warn("Discriminator column found at " +
inInfo.getBaseClass().map(Class::getCanonicalName).orElse("?"));
LOGGER.warn("Discriminator columns are ignored in case of inheritance type JOINED");
}
return null;
}
private final Path<?> getDiscriminatorColumn(final Optional<String> columnName, Optional<FromImpl<?, ?>> root,
final List<JPAPath> pathList) {
if (columnName.isPresent() && root.isPresent()) {
PathImpl<?> parent = root.get();
Path<?> columnPath = null;
for (final JPAPath p : pathList) {
if (p.getDBFieldName().equals(columnName.get()))
columnPath = new PathImpl<>(p, Optional.of(parent), root.get().st, tableAlias);
}
return columnPath;
}
return null;
}
private final List<JPAPath> getInheritanceRootPathList(Optional<FromImpl<?, ?>> root) {
if (root.isPresent()) {
try {
return root.get().st.getPathList();
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
return List.of();
}
@SuppressWarnings("unchecked")
private final Optional<FromImpl<?, ?>> getInheritanceRoot() {
var from = this;
while (from != null && from.inheritanceJoin.isPresent())
from = (FromImpl<Z, X>) from.inheritanceJoin.get();
return Optional.ofNullable(from);
}
private final Expression<Boolean> createInheritanceWhereSingleTable() {
final Optional<String> columnName = inInfo.getDiscriminatorColumn();
if (!columnName.isPresent())
throw new IllegalStateException("DiscriminatorColumn annotation missing at " + st.getTypeClass().getSuperclass()
.getCanonicalName());
Path<?> columnPath = null;
try {
for (final JPAPath a : st.getPathList()) {
if (a.getDBFieldName().equals(columnName.get()))
columnPath = new PathImpl<>(a, parent, st, tableAlias);
}
} catch (final ODataJPAModelException e) {
throw new IllegalStateException("Internal server error", e);
}
final DiscriminatorValue value = st.getTypeClass().getDeclaredAnnotation(DiscriminatorValue.class);
if (value == null)
throw new IllegalStateException("DiscriminatorValue annotation missing at " + st.getTypeClass()
.getCanonicalName());
return cb.equal(columnPath, value.value());
}
@SuppressWarnings("unchecked")
<U, V> FromImpl<U, V> determineParent() {
return (FromImpl<U, V>) this;
}
JPAStructuredType determineSource() throws ODataJPAModelException {
final JPAStructuredType source;
if (path.isPresent() && path.get().getLeaf().isComplex()) {
source = path.get().getLeaf().getStructuredType();
} else {
source = st;
}
return source;
}
@Override
List<JPAPath> getPathList() {
try {
return st.getPathList();
} catch (final ODataJPAModelException e) {
throw new IllegalStateException(e);
}
}
Optional<InheritanceType> getInheritanceType() {
return inInfo.getInheritanceType();
}
Optional<? extends AbstractJoinImp<X, ?>> getInheritanceJoin() {
return inheritanceJoin;
}
private JPAPath determinePath(final JPAAttribute joinAttribute) throws ODataJPAModelException {
if (path.isPresent())
return st.getPath(path.get().getAlias() + JPAPath.PATH_SEPARATOR + joinAttribute.getExternalName());
return st.getPath(joinAttribute.getExternalName());
}
@Nonnull
private JPAPath getJPAPath(final JPAAttribute joinAttribute) throws ODataJPAModelException {
final var jpaPath = determinePath(joinAttribute);
if (jpaPath != null)
return jpaPath;
else
throw new IllegalStateException();
}
private JPAAssociationAttribute getAssociation(final JPAStructuredType source, final String attributeName) {
try {
return source.getAssociation(attributeName);
} catch (final ODataJPAModelException e) {
throw new IllegalArgumentException(buildExceptionText(attributeName), e);
}
}
private boolean isSubtype(final Class<?> type) {
return st.getTypeClass().isAssignableFrom(type);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(final Object object) {
return super.equals(object);
}
Optional<String> getAlias(JPAPath jpaPath) {
if (isKeyPath(jpaPath))
return tableAlias;
if (inheritanceJoin.isPresent()) {
return Optional.ofNullable(
inheritanceJoin.get().getAlias(jpaPath)
.orElseGet(() -> getOwnAlias(jpaPath).orElse(null)));
}
return getOwnAlias(jpaPath);
}
final Optional<String> getOwnAlias(JPAPath jpaPath) {
try {
if (st.getDeclaredAttribute(jpaPath.getPath().get(0).getInternalName()).isPresent()) {
return tableAlias;
}
return Optional.empty();
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
} | 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SelectionImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/SelectionImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import static com.sap.olingo.jpa.processor.cb.impl.ExpressionImpl.SELECTION_REPLACEMENT;
import static com.sap.olingo.jpa.processor.cb.impl.ExpressionImpl.SELECTION_REPLACEMENT_REGEX;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Selection;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
/**
*
* @author Oliver Grande
*
* @param <X> the type of the selection item
*/
final class SelectionImpl<X> implements SqlSelection<X> {
private Optional<String> alias;
private final Class<X> resultType;
final Selection<?> selection;
protected Optional<List<Map.Entry<String, JPAPath>>> resolvedSelection = Optional.empty();
protected final AliasBuilder aliasBuilder;
SelectionImpl(final Selection<?> selection, final Class<X> resultType, final AliasBuilder aliasBuilder) {
this.resultType = resultType;
this.selection = selection;
if (selection instanceof Path<?>)
// Use a generated alias for standard columns
this.alias = Optional.empty();
else
// Take the given alias for ROW_NUMBER, so that no mapping is needed e.g. when used in WHERE clause
this.alias = Optional.ofNullable(selection.getAlias() == null || selection.getAlias().isEmpty()
? null : selection.getAlias());
this.aliasBuilder = aliasBuilder;
}
/**
* Assigns an alias to the selection item.
* Once assigned, an alias cannot be changed or reassigned.
* Returns the same selection item.
* @param name alias
* @return selection item
*/
@Override
public SqlSelection<X> alias(@Nonnull final String name) {
if (!alias.isPresent())
alias = Optional.of(name);
return this;
}
@Override
public StringBuilder asSQL(@Nonnull final StringBuilder statement) {
return ((SqlConvertible) selection)
.asSQL(statement)
.append(" ")
.append(getAlias().replaceAll(SELECTION_REPLACEMENT_REGEX, SELECTION_REPLACEMENT));
}
/**
* Return the alias assigned to the tuple element or creates on,
* if no alias has been assigned.
* @return alias if not set returns an empty string
*/
@Override
public String getAlias() {
return alias.orElseGet(this::createAlias);
}
/**
* Return the selection items composing a compound selection.
* Modifications to the list do not affect the query.
* @return list of selection items
* @throws IllegalStateException if selection is not a
* compound selection
*/
@Override
public List<Selection<?>> getCompoundSelectionItems() {
throw new IllegalStateException("Call of getCompoundSelectionItems on single selection");
}
/**
* Return the Java type of the tuple element.
* @return the Java type of the tuple element
*/
@Override
public Class<? extends X> getJavaType() {
return resultType;
}
@Override
public List<Map.Entry<String, JPAPath>> getResolvedSelection() {
return resolvedSelection.orElseGet(this::resolveSelectionLate);
}
/**
* Whether the selection item is a compound selection.
* @return boolean indicating whether the selection is a compound
* selection
*/
@Override
public boolean isCompoundSelection() {
return false;
}
protected List<Map.Entry<String, JPAPath>> resolveSelectionLate() {
return Collections.emptyList();
}
private String createAlias() {
alias = Optional.of(aliasBuilder.getNext());
return alias.get();
}
@SuppressWarnings("unchecked")
@Override
public Selection<X> getSelection() {
return (Selection<X>) 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/ParameterBuffer.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/ParameterBuffer.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.Expression;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sap.olingo.jpa.processor.cb.impl.ExpressionImpl.ParameterExpression;
class ParameterBuffer {
private static final Log LOG = LogFactory.getLog(ParameterBuffer.class);
private int index = 1;
private final Map<Integer, ParameterExpression<Object, Object>> parameterByHash;
ParameterBuffer() {
super();
parameterByHash = new HashMap<>();
}
<T, S> ParameterExpression<T, S> addValue(@Nonnull final S value) {
return this.addValue(value, null);
}
@SuppressWarnings("unchecked")
<T, S> ParameterExpression<T, S> addValue(@Nonnull final S value, final Expression<?> expression) {
ParameterExpression<T, S> param = new ParameterExpression<>(index, Objects.requireNonNull(value), expression);
if (!parameterByHash.containsKey(param.hashCode())) {
parameterByHash.put(param.hashCode(), (ParameterExpression<Object, Object>) param);
index++;
} else {
// Hibernate does not allow provisioning of parameter that are not used in a query
param = (ParameterExpression<T, S>) parameterByHash.get(param.hashCode());
LOG.trace("Parameter found in buffer: " + param);
}
return param;
}
Map<Integer, ParameterExpression<Object, Object>> getParameters() {
return parameterByHash;
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/JPAPathWrapper.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/JPAPathWrapper.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.criteria.Selection;
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;
class JPAPathWrapper implements JPAPath {
private final Selection<?> selection;
public JPAPathWrapper(final Selection<?> sel) {
this.selection = sel;
}
@Override
public int compareTo(final JPAPath o) {
return selection.getAlias().compareTo(o.getAlias());
}
@Override
public String getAlias() {
return selection.getAlias();
}
@Override
public String getDBFieldName() {
return null;
}
@Override
public JPAAttribute getLeaf() {
return new JPAAttributeWrapper(selection);
}
@Override
public List<JPAElement> getPath() {
return Collections.singletonList(getLeaf());
}
@Override
public boolean ignore() {
return false;
}
@Override
public boolean isPartOfGroups(final List<String> groups) {
return false;
}
@Override
public boolean isTransient() {
return false;
}
@Override
public String getPathAsString() {
return selection.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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/UpdateQueryImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/UpdateQueryImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.Query;
import jakarta.persistence.QueryTimeoutException;
import jakarta.persistence.TransactionRequiredException;
import jakarta.persistence.criteria.CriteriaUpdate;
class UpdateQueryImpl extends AbstractQueryImpl {
private final CriteriaUpdateImpl<?> updateQuery;
private final EntityManager em;
public UpdateQueryImpl(final EntityManager em, final CriteriaUpdate<?> updateQuery) {
super(((CriteriaUpdateImpl<?>) updateQuery).getParameterBuffer());
this.updateQuery = (CriteriaUpdateImpl<?>) updateQuery;
this.em = em;
}
/**
* @throws IllegalStateException
*/
@Override
public List<?> getResultList() {
throw new IllegalStateException();
}
/**
* @throws IllegalStateException
*/
@Override
public Object getSingleResult() {
throw new IllegalStateException();
}
/**
* Execute an update or delete statement.
* @return the number of entities updated or deleted
* @throws IllegalStateException if called for a Jakarta
* Persistence query language SELECT statement or for
* a criteria query
* @throws TransactionRequiredException if there is
* no transaction or the persistence context has not
* been joined to the transaction
* @throws QueryTimeoutException if the statement execution
* exceeds the query timeout value set and only
* the statement is rolled back
* @throws PersistenceException if the query execution exceeds
* the query timeout value set and the transaction
* is rolled back
*/
@Override
public int executeUpdate() {
final var query = em.createNativeQuery(updateQuery.asSQL(new StringBuilder()).toString());
copyParameter(query);
return query.executeUpdate();
}
/**
* @throws IllegalStateException
*/
@Override
public Query setMaxResults(final int maxResult) {
throw new IllegalStateException();
}
/**
* @throws IllegalStateException
*/
@Override
public int getMaxResults() {
return 0;
}
/**
* @throws IllegalStateException
*/
@Override
public Query setFirstResult(final int startPosition) {
throw new IllegalStateException();
}
/**
* @throws IllegalStateException
*/
@Override
public int getFirstResult() {
return 0;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(final Class<T> clazz) {
if (clazz.isAssignableFrom(this.getClass())) {
return (T) this;
}
throw new PersistenceException("Unable to unwrap " + clazz.getName());
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/InheritanceJoinReversed.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/InheritanceJoinReversed.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.metamodel.Attribute;
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.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.exceptions.InternalServerError;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
/**
* Represents a reversed join for an inheritance relation. From super-type to sub-type
* @param <Z> the sub-type
* @param <X> the super-type
*
* @author Oliver Grande
* @since 2.4.0
* @created 21.10.2025
*
*/
class InheritanceJoinReversed<Z, X> extends AbstractJoinImp<Z, X> {
private final JPAEntityType subType;
private List<FromImpl<?, ?>> inheritanceHierarchy;
InheritanceJoinReversed(@Nonnull final JPAEntityType targetType, @Nonnull final JPAEntityType superType,
@Nonnull final From<?, Z> root, @Nonnull final AliasBuilder aliasBuilder, @Nonnull final CriteriaBuilder cb) {
super(getHop(superType, targetType), root, aliasBuilder, cb);
this.subType = getHop(superType, targetType);
this.inheritanceJoin = Optional.empty();
this.getJoins().clear();
if (this.st != targetType) {
this.inheritanceJoin = Optional.of(
new InheritanceJoinReversed<>(targetType, this.st, this, aliasBuilder, cb));
this.inheritanceJoin.ifPresent(this.getJoins()::add);
}
}
@Override
public Predicate getOn() {
if (on == null) {
try {
createOn(subType.getInheritanceInformation().getReversedJoinColumnsList(), subType);
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
return on;
}
private static JPAEntityType getHop(@Nonnull final JPAEntityType superType, @Nonnull final JPAEntityType targetType) {
try {
JPAStructuredType result = targetType;
while (result.getBaseType() != null && result.getBaseType() != superType)
result = result.getBaseType();
return (JPAEntityType) result;
} catch (ODataJPAModelException e) {
throw new InternalServerError(e);
}
}
@Override
public Attribute<? super Z, ?> getAttribute() {
throw new NotImplementedException();
}
@Override
public JoinType getJoinType() {
return JoinType.INNER;
}
@SuppressWarnings("unchecked")
public From<Object, Object> getTarget() {
return inheritanceJoin.map(join -> (InheritanceJoinReversed<?, ?>) join)
.map(InheritanceJoinReversed::getTarget).orElse((From<Object, Object>) this);
}
@Override
Optional<String> getAlias(JPAPath jpaPath) {
if (isKeyPath(jpaPath))
return tableAlias;
final var hierarchy = getInheritanceHierarchy();
for (int i = hierarchy.size() - 1; i >= 0; i--) {
var alias = hierarchy.get(i).getOwnAlias(jpaPath);
if (alias.isPresent())
return alias;
}
return getOwnAlias(jpaPath);
}
private List<FromImpl<?, ?>> getInheritanceHierarchy() {
if (inheritanceHierarchy == null) {
inheritanceHierarchy = new ArrayList<>();
AbstractJoinImp<?, ?> start = this;
while (start != null &&
start.related != null &&
start.related instanceof AbstractJoinImp<?, ?>) {
inheritanceHierarchy.add((FromImpl<?, ?>) start.related);
start = (AbstractJoinImp<?, ?>) start.related;
}
}
return inheritanceHierarchy;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object other) {
return super.equals(other);
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TypeConverter.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/TypeConverter.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.time.temporal.Temporal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class TypeConverter {
private static final String NO_CONVERTER_FOUND_TEXT = "No converter found to convert ";
private static final Log LOGGER = LogFactory.getLog(TypeConverter.class);
private TypeConverter() {}
static Object convert(final Object source, final Class<?> target) { // NOSONAR
if (target == null || source == null)
return source;
if (!target.isAssignableFrom(source.getClass())) {
if (target == String.class) {
return source.toString();
}
if (boxed(target) == Boolean.class && source instanceof final String asString)
return Boolean.valueOf(asString);
if (boxed(target) == Boolean.class && source instanceof final Number asNumber)
return asNumber.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
if (source instanceof final Number asNumber && Number.class.isAssignableFrom(boxed(target))) {
return convertNumber(asNumber, target);
}
if (Temporal.class.isAssignableFrom(target)) {
return convertTemporal(source, target);
}
if (boxed(target) == Character.class && source instanceof final String asString) {
return convertToCharacter(asString);
}
if (target == Duration.class) {
return convertDuration(source);
}
if (target == Timestamp.class) {
return convertTimestamp(source);
} else {
LOGGER.debug(NO_CONVERTER_FOUND_TEXT + source.getClass().getSimpleName() + " to " + target
.getSimpleName());
throw new IllegalArgumentException(createCastException(source, target));
}
}
return target.cast(source);
}
private static Character convertToCharacter(final String source) {
if (source.length() > 1) {
LOGGER.debug("Implicit conversion to Character from String only supported if String not longer than 1");
throw new IllegalArgumentException("String to long");
}
if (source.isEmpty())
return ' ';
return source.charAt(0);
}
private static Duration convertDuration(final Object source) {
if (boxed(source.getClass()) == Long.class)
return Duration.ofSeconds((long) source);
if (source.getClass() == String.class)
return Duration.parse((String) source);
LOGGER.debug(NO_CONVERTER_FOUND_TEXT + source.getClass().getSimpleName() + " to Duration");
throw new IllegalArgumentException(createCastException(source, Duration.class));
}
private static Temporal convertTemporal(final Object source, final Class<?> target) { // NOSONAR
if (temporalConversionAllowed(source.getClass(), target)) {
try {
if (target == Instant.class) {
return convertTemporalToInstant(source);
}
if (target == LocalDate.class) {
return convertTemporalToLocalDate(source);
}
if (target == LocalDateTime.class) {
return convertTemporalToLocalDateTime(source);
}
if (target == LocalTime.class) {
return convertTemporalToLocalTime(source);
}
if (target == OffsetTime.class) {
return OffsetTime.parse((String) source);
}
if (target == OffsetDateTime.class) {
return convertTemporalToOffsetDateTime(source);
}
} catch (final DateTimeParseException e) {
throw new IllegalArgumentException(e);
}
}
throw new IllegalArgumentException(createCastException(source, target));
}
private static LocalTime convertTemporalToLocalTime(final Object source) {
if (source.getClass() == Time.class)
return ((Time) source).toLocalTime();
return LocalTime.parse((String) source);
}
private static LocalDateTime convertTemporalToLocalDateTime(final Object source) {
if (source.getClass() == Timestamp.class)
return ((Timestamp) source).toLocalDateTime();
return LocalDateTime.parse((String) source);
}
private static LocalDate convertTemporalToLocalDate(final Object source) {
if (source.getClass() == Date.class)
return ((Date) source).toLocalDate();
if (source.getClass() == Timestamp.class)
return ((Timestamp) source).toLocalDateTime().toLocalDate();
return LocalDate.parse((String) source);
}
private static Instant convertTemporalToInstant(final Object source) {
if (source.getClass() == Long.class)
return Instant.ofEpochMilli(((Number) source).longValue());
if (source.getClass() == String.class)
return Instant.parse((String) source);
return ((Timestamp) source).toInstant();
}
private static OffsetDateTime convertTemporalToOffsetDateTime(final Object source) {
if (source.getClass() == Timestamp.class) {
return OffsetDateTime.ofInstant(((Timestamp) source).toInstant(), ZoneId.of("UTC"));
}
return OffsetDateTime.parse((String) source);
}
private static Timestamp convertTimestamp(Object source) {
if (source instanceof LocalDateTime ldt)
return Timestamp.valueOf(ldt);
if (source instanceof LocalDate ld)
return Timestamp.valueOf(LocalDateTime.of(ld, LocalTime.of(0, 0)));
if (source instanceof String s)
return Timestamp.valueOf(s);
LOGGER.debug(NO_CONVERTER_FOUND_TEXT + source.getClass().getSimpleName() + " to Timestamp");
throw new IllegalArgumentException(createCastException(source, Timestamp.class));
}
public static Class<?> boxed(final Class<?> javaType) {
if (javaType == int.class) return Integer.class;
if (javaType == long.class) return Long.class;
if (javaType == boolean.class) return Boolean.class;
if (javaType == byte.class) return Byte.class;
if (javaType == char.class) return Character.class;
if (javaType == float.class) return Float.class;
if (javaType == short.class) return Short.class;
if (javaType == double.class) return Double.class;
return javaType;
}
private static Object convertNumber(final Number source, final Class<?> target) { // NOSONAR
if (numberConversionAllowed(source.getClass(), target)) {
try {
if (boxed(target) == Long.class) {
return source.longValue();
}
if (boxed(target) == Integer.class) {
return source.intValue();
}
if (boxed(target) == Short.class) {
return source.shortValue();
}
if (boxed(target) == Byte.class) {
return source.byteValue();
}
if (boxed(target) == Float.class) {
return source.floatValue();
}
if (boxed(target) == Double.class) {
return source.doubleValue();
}
if (target == BigInteger.class) {
return BigInteger.valueOf(source.longValue());
}
if (target == BigDecimal.class) {
return convertToBigDecimal(source);
}
} catch (final NumberFormatException e) {
throw new IllegalArgumentException(e);
}
}
throw new IllegalArgumentException(createCastException(source, target));
}
private static Object convertToBigDecimal(final Number result) {
if (result instanceof Float || result instanceof Double) {
final Double d = result.doubleValue();
if (Double.isInfinite(d))
throw new IllegalArgumentException(
String.format("Type cast error: Can't convert infinity value of type '%s' to BigDecimal. @Convert required",
result));
if (Double.isNaN(d))
throw new IllegalArgumentException(
"Type cast error: Can't convert 'Not A Number' to BigDecimal. @Convert required");
return BigDecimal.valueOf(result.doubleValue());
}
return BigDecimal.valueOf(result.longValue());
}
private static String createCastException(final Object result, final Class<?> target) {
return String.format("Type cast error: Can't convert '%s' to '%s'. @Convert required",
result.getClass(), target);
}
private static boolean numberConversionAllowed(final Class<?> source, final Class<?> target) { // NOSONAR
if (target == Short.class || target == short.class) return source == Byte.class || source == Integer.class;
if (target == Integer.class || target == int.class) return source == Byte.class || source == Short.class
|| source == Long.class;
if (target == Long.class || target == long.class) return source == Byte.class || source == Short.class
|| source == Integer.class || source == BigInteger.class || source == BigDecimal.class;
if (target == BigInteger.class) return source == Byte.class || source == Short.class || source == Integer.class
|| source == Long.class || source == BigDecimal.class;
if (target == Float.class || target == float.class) return source == Byte.class || source == Short.class
|| source == Integer.class || source == Long.class || source == BigInteger.class || source == BigDecimal.class;
if (target == Double.class || target == double.class) return source == Byte.class || source == Short.class
|| source == Integer.class || source == Long.class || source == BigInteger.class || source == BigDecimal.class
|| source == Float.class;
if (target == BigDecimal.class) return source == Byte.class || source == Short.class || source == Integer.class
|| source == Long.class || source == BigInteger.class || source == Float.class || source == Double.class;
return false;
}
private static boolean temporalConversionAllowed(final Class<?> source, final Class<?> target) { // NOSONAR
if (target == Instant.class) return source == Long.class || source == String.class || source == Timestamp.class;
if (target == LocalDate.class) return source == Date.class || source == Timestamp.class || source == String.class;
if (target == LocalDateTime.class) return source == Timestamp.class || source == String.class;
if (target == LocalTime.class) return source == Time.class || source == String.class;
if (target == OffsetDateTime.class) return source == Timestamp.class || source == String.class;
if (target == OffsetTime.class) return source == String.class;
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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/ExpressionImpl.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/ExpressionImpl.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Parameter;
import jakarta.persistence.criteria.CriteriaBuilder.Coalesce;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Selection;
import jakarta.persistence.criteria.Subquery;
import jakarta.persistence.metamodel.Bindable;
import jakarta.persistence.metamodel.MapAttribute;
import jakarta.persistence.metamodel.PluralAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
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.WindowFunction;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlFunction;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlOperator;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlParameter;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.exceptions.NotImplementedException;
import com.sap.olingo.jpa.processor.cb.exceptions.SqlParameterException;
import com.sap.olingo.jpa.processor.cb.joiner.SqlConvertible;
import com.sap.olingo.jpa.processor.cb.joiner.StringBuilderCollector;
abstract class ExpressionImpl<T> implements Expression<T>, SqlConvertible {
public static final String OPENING_BRACKET = "(";
public static final String CLOSING_BRACKET = ")";
public static final String DOT = ".";
public static final String SELECTION_REPLACEMENT = "_";
public static final String SELECTION_REPLACEMENT_REGEX = "\\.|/";
protected Optional<String> alias = Optional.empty();
/**
* Assigns an alias to the selection item.
* Once assigned, an alias cannot be changed or reassigned.
* Returns the same selection item.
* @param name alias
* @return selection item
*/
@Override
public Selection<T> alias(final String name) {
if (alias.isPresent())
throw new IllegalAccessError("Alias can only be set once");
alias = Optional.of(name);
return this;
}
/**
* Perform a typecast upon the expression, returning a new
* expression object.
* This method does not cause type conversion:
* the runtime type is not changed.
* Warning: may result in a runtime failure.
* @param type intended type of the expression
* @return new expression of the given type
*/
@Override
public <X> Expression<X> as(final Class<X> type) {
throw new NotImplementedException();
}
@Override
public String getAlias() {
return alias.orElse("");
}
@Override
public List<Selection<?>> getCompoundSelectionItems() {
throw new NotImplementedException();
}
@Override
public Class<? extends T> getJavaType() {
return null;
}
@Override
public Predicate in(final Collection<?> values) {
throw new NotImplementedException();
}
@Override
public Predicate in(final Expression<?>... values) {
throw new NotImplementedException();
}
@Override
public Predicate in(final Expression<Collection<?>> values) {
throw new NotImplementedException();
}
@Override
public Predicate in(final Object... values) {
throw new NotImplementedException();
}
@Override
public boolean isCompoundSelection() {
return false;
}
/**
* Create a predicate to test whether the expression is not null.
* @return predicate testing whether the expression is not null
*/
@Override
public Predicate isNotNull() {
throw new NotImplementedException();
}
/**
* Create a predicate to test whether the expression is null.
* @return predicate testing whether the expression is null
*/
@Override
public Predicate isNull() {
throw new NotImplementedException();
}
void checkParameterCount(final int act, final int max, final String function) {
if (act < max)
throw new SqlParameterException("Not all parameter supported for: " + function);
}
void addParameter(final ProcessorSqlParameter parameter, final List<CharSequence> parameterValues,
final SqlConvertible value) {
parameterValues.add(parameter.keyword());
parameterValues.add(value.asSQL(new StringBuilder()));
}
static class AggregationExpression<N extends Number> extends ExpressionImpl<N> {
private final SqlAggregation function;
private final SqlConvertible expression;
AggregationExpression(@Nonnull final SqlAggregation function, @Nonnull final Expression<?> expression) {
this.function = Objects.requireNonNull(function);
this.expression = Objects.requireNonNull((SqlConvertible) expression);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(function)
.append(OPENING_BRACKET);
return expression(statement)
.append(CLOSING_BRACKET);
}
private StringBuilder expression(final StringBuilder statement) {
if (expression instanceof final FromImpl<?, ?> from) {
final String tableAlias = from.tableAlias.orElseThrow(IllegalStateException::new);
try {
final List<JPAAttribute> keys = from.st.getKey();
statement
.append(tableAlias)
.append(DOT)
.append(getJPAPath(from, keys).getDBFieldName());
} catch (final ODataJPAModelException e) {
throw new IllegalArgumentException(e);
}
return statement;
} else {
return expression.asSQL(statement);
}
}
@Nonnull
private JPAPath getJPAPath(final FromImpl<?, ?> from, final List<JPAAttribute> keys) throws ODataJPAModelException {
final var jpaPath = from.st.getPath(keys.get(0).getExternalName(), false);
if (jpaPath != null)
return jpaPath;
else
throw new IllegalStateException();
}
SqlConvertible getExpression() {
return expression;
}
}
static class ArithmeticExpression<N extends Number> extends ExpressionImpl<N> {
private final SqlConvertible left;
private final SqlConvertible right;
private final SqlArithmetic operation;
ArithmeticExpression(@Nonnull final Expression<? extends N> expression, @Nonnull final Expression<? extends N> y,
@Nonnull final SqlArithmetic operation) {
this.left = (SqlConvertible) Objects.requireNonNull(expression);
this.right = (SqlConvertible) Objects.requireNonNull(y);
this.operation = Objects.requireNonNull(operation);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
left.asSQL(statement.append(OPENING_BRACKET))
.append(" ")
.append(operation)
.append(" ");
return right.asSQL(statement)
.append(CLOSING_BRACKET);
}
}
static class CoalesceExpression<T> extends ExpressionImpl<T> implements Coalesce<T> {
private final List<Expression<T>> values;
CoalesceExpression() {
super();
this.values = new ArrayList<>();
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(SqlKeyWords.COALESCE)
.append(OPENING_BRACKET);
statement.append(values.stream().collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
return statement.append(CLOSING_BRACKET);
}
@SuppressWarnings("unchecked")
@Override
public Coalesce<T> value(@Nonnull final Expression<? extends T> value) {
values.add((Expression<T>) value);
return this;
}
@Override
public Coalesce<T> value(@Nonnull final T value) {
throw new NotImplementedException();
}
}
static class ConcatExpression extends ExpressionImpl<String> {
private final SqlConvertible first;
private final SqlConvertible second;
private final ProcessorSqlPatternProvider sqlPattern;
ConcatExpression(@Nonnull final Expression<String> first, @Nonnull final Expression<String> second,
final ProcessorSqlPatternProvider sqlPattern) {
this.first = (SqlConvertible) Objects.requireNonNull(first);
this.second = (SqlConvertible) Objects.requireNonNull(second);
this.sqlPattern = sqlPattern;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
final var concatenateClause = sqlPattern.getConcatenatePattern();
if (concatenateClause instanceof final ProcessorSqlFunction function) {
statement.append(function.function())
.append(OPENING_BRACKET);
first.asSQL(statement)
.append(function.parameters().get(1).keyword());
second.asSQL(statement);
return statement.append(CLOSING_BRACKET);
} else {
final var operation = (ProcessorSqlOperator) concatenateClause;
statement.append(OPENING_BRACKET);
first.asSQL(statement)
.append(operation.parameters().get(1).keyword());
second.asSQL(statement);
return statement.append(CLOSING_BRACKET);
}
}
}
static class DistinctExpression<T> extends ExpressionImpl<T> {
private final SqlConvertible left;
DistinctExpression(@Nonnull final Expression<?> expression) {
this.left = (SqlConvertible) Objects.requireNonNull(expression);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
if (left instanceof FromImpl<?, ?>) {
try {
final FromImpl<?, ?> from = ((FromImpl<?, ?>) left);
statement.append(SqlKeyWords.DISTINCT)
.append(OPENING_BRACKET);
statement.append(from.st.getKey().stream()
.map(a -> from.get(a.getInternalName()))
.collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
return statement.append(CLOSING_BRACKET);
} catch (final ODataJPAModelException e) {
throw new IllegalStateException(e);
}
}
return left.asSQL(statement.append(SqlKeyWords.DISTINCT).append(OPENING_BRACKET)).append(CLOSING_BRACKET);
}
}
static class FunctionExpression<T> extends ExpressionImpl<T> {
private final String functionName;
private final Class<T> type;
private final List<Expression<Object>> args;
FunctionExpression(@Nonnull final String name, @Nonnull final Class<T> type, final List<Expression<Object>> args) {
this.functionName = Objects.requireNonNull(name);
this.type = Objects.requireNonNull(type);
this.args = Objects.requireNonNull(args);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(functionName).append(OPENING_BRACKET);
statement.append(args.stream().collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
return statement.append(CLOSING_BRACKET);
}
@Override
public Class<? extends T> getJavaType() {
return type;
}
}
static class LocateExpression extends ExpressionImpl<Integer> {
private final SqlConvertible expression;
private final SqlConvertible pattern;
private final Optional<SqlConvertible> from;
private final ProcessorSqlPatternProvider sqlPattern;
LocateExpression(@Nonnull final Expression<String> expression, @Nonnull final Expression<String> pattern,
final Expression<Integer> from, @Nonnull final ProcessorSqlPatternProvider sqlPattern) {
this.expression = (SqlConvertible) Objects.requireNonNull(expression);
this.pattern = (SqlConvertible) Objects.requireNonNull(pattern);
this.from = Optional.ofNullable((SqlConvertible) from);
this.sqlPattern = sqlPattern;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
// LOCATE(<pattern>, <string>, <from>)
final var function = sqlPattern.getLocatePattern();
checkParameterCount(function.parameters().size(), from.isPresent() ? 3 : 2,
SqlStringFunctions.LOCATE.toString());
final List<CharSequence> parameterValues = new ArrayList<>(5);
statement.append(function.function())
.append(OPENING_BRACKET);
for (final var parameter : function.parameters()) {
switch (parameter.parameter()) {
case ProcessorSqlPatternProvider.SEARCH_STRING_PLACEHOLDER -> addParameter(parameter, parameterValues,
pattern);
case ProcessorSqlPatternProvider.VALUE_PLACEHOLDER -> addParameter(parameter, parameterValues,
expression);
case ProcessorSqlPatternProvider.START_PLACEHOLDER -> from.ifPresent(f -> addParameter(parameter,
parameterValues, f));
default -> throw new IllegalArgumentException(parameter.parameter()
+ " not supported for function LOCATE only supports function as pattern");
}
}
statement.append(parameterValues.stream().collect(Collectors.joining()));
return statement.append(CLOSING_BRACKET);
}
}
static class LengthExpression extends ExpressionImpl<Integer> {
private final SqlConvertible left;
private final ProcessorSqlPatternProvider sqlPattern;
LengthExpression(@Nonnull final Expression<?> expression, @Nonnull final ProcessorSqlPatternProvider sqlPattern) {
this.left = (SqlConvertible) Objects.requireNonNull(expression);
this.sqlPattern = Objects.requireNonNull(sqlPattern);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
final var function = sqlPattern.getLengthPattern();
statement.append(function.function()).append(OPENING_BRACKET);
return left.asSQL(statement).append(CLOSING_BRACKET);
}
}
static final class ParameterExpression<T, S> extends ExpressionImpl<T> implements Parameter<T> {
private final Integer index;
private final S value;
private Optional<AttributeConverter<S, T>> converter;
private Optional<JPAPath> jpaPath;
ParameterExpression(final Integer i, final S value) {
this.index = i;
this.value = value;
this.converter = Optional.empty();
this.jpaPath = Optional.empty();
}
ParameterExpression(final Integer i, final S value, @Nullable final Expression<?> expression) {
this.index = i;
this.value = value;
setPath(expression);
}
@SuppressWarnings("unchecked")
T getValue() {
if (converter.isPresent())
return converter.get().convertToDatabaseColumn(value);
if (jpaPath.isPresent() && jpaPath.get().getLeaf().isEnum())
return (T) ((Number) ((Enum<?>) value).ordinal());
return (T) value;
}
void setPath(@Nullable final Expression<?> expression) {
if (expression instanceof PathImpl && ((PathImpl<?>) expression).path.isPresent()) {
jpaPath = Optional.of(((PathImpl<?>) expression).path.get()); // NOSONAR
converter = Optional.ofNullable(jpaPath.get().getLeaf().getRawConverter());
} else {
this.converter = Optional.empty();
this.jpaPath = Optional.empty();
}
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
return statement.append("?").append(index.toString());
}
@Override
public String getName() {
return index.toString();
}
@Override
public Integer getPosition() {
return index;
}
@SuppressWarnings("unchecked")
@Override
public Class<T> getParameterType() {
return (Class<T>) value.getClass();
}
@Override
public Class<? extends T> getJavaType() {
return getParameterType();
}
@Override
public int hashCode() {
return Objects.hash(jpaPath, value);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) return true;
if (!(obj instanceof ParameterExpression)) return false;
final ParameterExpression<?, ?> other = (ParameterExpression<?, ?>) obj;
return Objects.equals(jpaPath, other.jpaPath) && Objects.equals(value, other.value);
}
@Override
public String toString() {
return "ParameterExpression [jpaPath=" + jpaPath + ", value=" + value + ", index=" + index + "]";
}
}
static final class SubQuery<X> extends ExpressionImpl<X> {
private final SqlConvertible query;
private final SqlSubQuery operator;
SubQuery(@Nonnull final Subquery<?> subquery, @Nonnull final SqlSubQuery operator) {
this.query = (SqlConvertible) Objects.requireNonNull(subquery);
this.operator = operator;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(operator)
.append(" ")
.append(OPENING_BRACKET);
return query.asSQL(statement).append(CLOSING_BRACKET);
}
}
static class SubstringExpression extends ExpressionImpl<String> {
private final SqlConvertible expression;
private final SqlConvertible from;
private final Optional<SqlConvertible> length;
private final ProcessorSqlPatternProvider sqlPattern;
SubstringExpression(@Nonnull final Expression<String> expression, @Nonnull final Expression<Integer> from,
final Expression<Integer> length, @Nonnull final ProcessorSqlPatternProvider sqlPattern) {
this.expression = (SqlConvertible) Objects.requireNonNull(expression);
this.from = (SqlConvertible) Objects.requireNonNull(from);
this.length = Optional.ofNullable((SqlConvertible) length);
this.sqlPattern = Objects.requireNonNull(sqlPattern);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
final var function = sqlPattern.getSubStringPattern();
checkParameterCount(function.parameters().size(), length.isPresent() ? 3 : 2,
SqlStringFunctions.SUBSTRING.toString());
final List<CharSequence> parameterValues = new ArrayList<>(3);
statement.append(function.function())
.append(OPENING_BRACKET);
for (final var parameter : function.parameters()) {
switch (parameter.parameter()) {
case ProcessorSqlPatternProvider.VALUE_PLACEHOLDER -> addParameter(parameter, parameterValues, expression);
case ProcessorSqlPatternProvider.START_PLACEHOLDER -> addParameter(parameter, parameterValues, from);
case ProcessorSqlPatternProvider.LENGTH_PLACEHOLDER -> length.ifPresent(f -> addParameter(parameter,
parameterValues, f));
default -> throw new IllegalArgumentException(parameter.parameter()
+ " not supported for function SUBSTRING");
}
}
statement.append(parameterValues.stream().collect(Collectors.joining()));
return statement.append(CLOSING_BRACKET);
}
}
static class TimeExpression<T> extends ExpressionImpl<T> {
private final SqlTimeFunctions function;
TimeExpression(@Nonnull final SqlTimeFunctions function) {
this.function = Objects.requireNonNull(function);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
return statement.append(function);
}
}
static class UnaryFunctionalExpression<T> extends ExpressionImpl<T> {
private final SqlConvertible left;
private final SqlStringFunctions function;
UnaryFunctionalExpression(@Nonnull final Expression<?> expression, @Nonnull final SqlStringFunctions function) {
this.left = (SqlConvertible) Objects.requireNonNull(expression);
this.function = Objects.requireNonNull(function);
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(function).append(OPENING_BRACKET);
return left.asSQL(statement).append(CLOSING_BRACKET);
}
}
static class WindowFunctionExpression<T> extends ExpressionImpl<T> implements WindowFunction<T> {
private final SqlWindowFunctions function;
private Optional<List<Order>> orderBy;
private Optional<List<Path<Comparable<?>>>> partitionBy;
WindowFunctionExpression(@Nonnull final SqlWindowFunctions function) {
this.function = function;
this.orderBy = Optional.empty();
this.partitionBy = Optional.empty();
}
// https://www.h2database.com/html/functions-window.html
// window_function_name ( expression ) OVER (partition_clause order_clause frame_clause)
@Override
public StringBuilder asSQL(final StringBuilder statement) {
statement.append(function)
.append(OPENING_BRACKET)
.append(CLOSING_BRACKET)
.append(" OVER")
.append(OPENING_BRACKET);
partitionBy.ifPresent(paths -> {
statement
.append(" ")
.append(SqlKeyWords.PARTITION)
.append(" ");
statement.append(paths.stream().collect(new StringBuilderCollector.ExpressionCollector(statement, ", ")));
});
orderBy.ifPresent(o -> {
statement
.append(" ")
.append(SqlKeyWords.ORDERBY)
.append(" ");
statement.append(o.stream().collect(new StringBuilderCollector.OrderCollector(statement, ", ")));
});
return statement.append(CLOSING_BRACKET);
}
@Override
public WindowFunction<T> orderBy(final Order... o) {
return orderBy(Arrays.asList(o));
}
@Override
public WindowFunction<T> orderBy(final List<Order> o) {
this.orderBy = Optional.ofNullable(o);
return this;
}
@Override
public WindowFunction<T> partitionBy(@SuppressWarnings("unchecked") final Path<Comparable<?>>... paths) {
return partitionBy(Arrays.asList(paths));
}
@Override
public WindowFunction<T> partitionBy(final List<Path<Comparable<?>>> paths) {
this.partitionBy = Optional.ofNullable(paths);
return this;
}
@Override
public Path<T> asPath(final String tableAlias) {
return new ExpressionPath<>(alias, tableAlias);
}
}
static class ExpressionPath<T> extends ExpressionImpl<T> implements Path<T> {
private final Optional<String> dbFieldName;
private final Optional<String> tableAlias;
ExpressionPath(final Optional<String> dbFieldName, final String tableAlias) {
this.dbFieldName = dbFieldName;
this.tableAlias = Optional.of(tableAlias);
}
ExpressionPath(final String dbFieldName, final Optional<String> tableAlias) {
this.dbFieldName = Optional.of(dbFieldName);
this.tableAlias = tableAlias;
}
@Override
public StringBuilder asSQL(final StringBuilder statement) {
tableAlias.ifPresent(path -> {
statement.append(path);
statement.append(DOT);
});
statement.append(dbFieldName.orElseThrow(() -> new IllegalStateException("Missing name")));
return statement;
}
@Override
public Bindable<T> getModel() {
throw new NotImplementedException();
}
@Override
public Path<?> getParentPath() {
throw new NotImplementedException();
}
@Override
public <Y> Path<Y> get(final SingularAttribute<? super T, Y> attribute) {
throw new NotImplementedException();
}
@Override
public <E, C extends Collection<E>> Expression<C> get(final PluralAttribute<T, C, E> collection) {
throw new NotImplementedException();
}
@Override
public <K, V, M extends Map<K, V>> Expression<M> get(final MapAttribute<T, K, V> map) {
throw new NotImplementedException();
}
@Override
public Expression<Class<? extends T>> type() {
throw new NotImplementedException();
}
@Override
public <Y> Path<Y> get(final String attributeName) {
throw new NotImplementedException();
}
}
}
| 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/InheritanceInfo.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/impl/InheritanceInfo.java | package com.sap.olingo.jpa.processor.cb.impl;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jakarta.persistence.DiscriminatorColumn;
import jakarta.persistence.Entity;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
class InheritanceInfo {
private static final Log LOGGER = LogFactory.getLog(InheritanceInfo.class);
private final Optional<InheritanceType> inType;
private final Optional<Class<?>> baseClass;
private final Optional<String> discriminatorColumn;
InheritanceInfo(@Nonnull final JPAEntityType type) {
baseClass = Optional.ofNullable(determineBaseClass(type));
inType = Optional.ofNullable(baseClass.map(this::determineInType).orElse(null));
discriminatorColumn = Optional.ofNullable(baseClass.map(this::determineColumn).orElse(null));
}
/**
*
* @return Root of an inheritance hierarchy
*/
Optional<Class<?>> getBaseClass() {
return baseClass;
}
Optional<String> getDiscriminatorColumn() {
return discriminatorColumn;
}
Optional<InheritanceType> getInheritanceType() {
return inType;
}
boolean hasInheritance() {
return inType.isPresent();
}
@CheckForNull
private Class<?> determineBaseClass(final JPAEntityType et) {
if (et != null && et.getTypeClass().getSuperclass() != null) {
final Class<?> superClass = et.getTypeClass().getSuperclass();
return determineInheritanceByClass(et, superClass);
}
return null;
}
private String determineColumn(@Nonnull final Class<?> clazz) {
return inType
.map(type -> clazz.getDeclaredAnnotation(DiscriminatorColumn.class))
.map(column -> column.name())
.orElse(null);
}
@CheckForNull
private Class<?> determineInheritanceByClass(final JPAEntityType et, final Class<?> clazz) {
final Entity jpaEntity = clazz.getDeclaredAnnotation(Entity.class);
if (jpaEntity != null) {
final Inheritance inheritance = clazz.getDeclaredAnnotation(Inheritance.class);
if (inheritance != null) {
return clazz;
} else {
final Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
return determineInheritanceByClass(et, superClass);
} else {
LOGGER.debug("Cloud not find InheritanceType for " + et.getInternalName());
}
}
}
return null;
}
private InheritanceType determineInType(@Nonnull final Class<?> baseClass) {
final Inheritance inheritance = baseClass.getDeclaredAnnotation(Inheritance.class);
return inheritance.strategy();
}
} | 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-cb/src/main/java/com/sap/olingo/jpa/processor/cb/api/EntityManagerFactoryWrapper.java | jpa/odata-jpa-processor-cb/src/main/java/com/sap/olingo/jpa/processor/cb/api/EntityManagerFactoryWrapper.java | package com.sap.olingo.jpa.processor.cb.api;
import java.util.Map;
import jakarta.persistence.Cache;
import jakarta.persistence.EntityGraph;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceUnitUtil;
import jakarta.persistence.Query;
import jakarta.persistence.SynchronizationType;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.metamodel.Metamodel;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.cb.impl.EntityManagerWrapper;
public final class EntityManagerFactoryWrapper implements EntityManagerFactory {
private final EntityManagerFactory emf;
private final JPAServiceDocument sd;
private final ProcessorSqlPatternProvider pattern;
public EntityManagerFactoryWrapper(final EntityManagerFactory emf, final JPAServiceDocument sd,
final ProcessorSqlPatternProvider pattern) {
super();
this.emf = emf;
this.sd = sd;
this.pattern = pattern;
}
@Override
public EntityManager createEntityManager() {
return new EntityManagerWrapper(emf.createEntityManager(), sd, pattern);
}
@Override
public EntityManager createEntityManager(@SuppressWarnings("rawtypes") final Map map) {
return new EntityManagerWrapper(emf.createEntityManager(map), sd, pattern);
}
@Override
public EntityManager createEntityManager(final SynchronizationType synchronizationType) {
return new EntityManagerWrapper(emf.createEntityManager(synchronizationType), sd, pattern);
}
@Override
public EntityManager createEntityManager(final SynchronizationType synchronizationType,
@SuppressWarnings("rawtypes") final Map map) {
return new EntityManagerWrapper(emf.createEntityManager(synchronizationType, map), sd, pattern);
}
@Override
public CriteriaBuilder getCriteriaBuilder() {
try (EntityManager em = new EntityManagerWrapper(emf.createEntityManager(), sd, pattern)) {
return em.getCriteriaBuilder();
}
}
@Override
public Metamodel getMetamodel() {
return emf.getMetamodel();
}
@Override
public boolean isOpen() {
return emf.isOpen();
}
@Override
public void close() {
emf.close();
}
@Override
public Map<String, Object> getProperties() {
return emf.getProperties();
}
@Override
public Cache getCache() {
return emf.getCache();
}
@Override
public PersistenceUnitUtil getPersistenceUnitUtil() {
return emf.getPersistenceUnitUtil();
}
@Override
public void addNamedQuery(final String name, final Query query) {
emf.addNamedQuery(name, query);
}
@Override
public <T> T unwrap(final Class<T> clazz) {
return emf.unwrap(clazz);
}
@Override
public <T> void addNamedEntityGraph(final String graphName, final EntityGraph<T> entityGraph) {
emf.addNamedEntityGraph(graphName, entityGraph);
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/TestGroupBase.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestGroupBase.java | package com.sap.olingo.jpa.processor.core.util;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import jakarta.persistence.criteria.Root;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.junit.jupiter.api.BeforeEach;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractJoinQuery;
import com.sap.olingo.jpa.processor.core.query.JPAJoinQuery;
public class TestGroupBase extends TestBase {
protected JPAAbstractJoinQuery cut;
protected JPAEntityType jpaEntityType;
protected Root<?> root;
protected JPAODataSessionContextAccess context;
protected UriInfo uriInfo;
protected JPAODataInternalRequestContext requestContext;
protected OData odata;
public TestGroupBase() {
super();
}
@BeforeEach
public void setup() throws ODataException, ODataJPAIllegalAccessException {
uriInfo = buildUriInfo("BusinessPartnerWithGroupss", "BusinessPartnerWithGroups");
helper = new TestHelper(emf, PUNIT_NAME);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
jpaEntityType = helper.getJPAEntityType("BusinessPartnerWithGroupss");
createHeaders();
context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages),
emf, dataSource, null, null, null);
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
odata = OData.newInstance();
requestContext = new JPAODataInternalRequestContext(externalContext, context, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables = new HashMap<>();
joinTables.put(jpaEntityType.getExternalName(), root);
}
protected UriInfo buildUriInfo(final String esName, final String etName) {
final UriInfo uriInfo = mock(UriInfo.class);
final EdmEntitySet odataEs = mock(EdmEntitySet.class);
final EdmEntityType odataType = mock(EdmEntityType.class);
final List<UriResource> resources = new ArrayList<>();
final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(0));
when(esResource.getEntitySet()).thenReturn(odataEs);
when(esResource.getKind()).thenReturn(UriResourceKind.entitySet);
when(esResource.getType()).thenReturn(odataType);
when(odataEs.getName()).thenReturn(esName);
when(odataEs.getEntityType()).thenReturn(odataType);
when(odataType.getNamespace()).thenReturn(PUNIT_NAME);
when(odataType.getName()).thenReturn(etName);
resources.add(esResource);
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/test/java/com/sap/olingo/jpa/processor/core/util/TupleDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TupleDouble.java | package com.sap.olingo.jpa.processor.core.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import jakarta.persistence.TupleElement;
public class TupleDouble implements Tuple {
public final Map<String, Object> elementMap;
public TupleDouble(final Map<String, Object> elementList) {
super();
this.elementMap = elementList;
}
@Override
public <X> X get(final TupleElement<X> tupleElement) {
return null;
}
@Override
public Object get(final String alias) {
return elementMap.get(alias);
}
@Override
public Object get(final int i) {
return null;
}
@Override
public <X> X get(final String alias, final Class<X> type) {
return null;
}
@Override
public <X> X get(final int i, final Class<X> type) {
return null;
}
@Override
public List<TupleElement<?>> getElements() {
final List<TupleElement<?>> elementList = new ArrayList<>();
for (final String alias : elementMap.keySet())
elementList.add(new TupleElementDouble(alias, elementMap.get(alias)));
return elementList;
}
@Override
public Object[] toArray() {
final List<Object> elementList = new ArrayList<>();
for (final String alias : elementMap.keySet())
elementList.add(elementMap.get(alias));
return elementList.toArray();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
public class UriResourceNavigationDouble implements UriResourceNavigation {
private final EdmType type;
private final EdmNavigationProperty property;
public UriResourceNavigationDouble(final EdmEntityType navigationTargetEntity) {
this(navigationTargetEntity, null);
}
public UriResourceNavigationDouble(final EdmType type, final EdmNavigationProperty property) {
super();
this.type = type;
this.property = property;
}
@Override
public EdmType getType() {
return type;
}
@Override
public boolean isCollection() {
fail();
return false;
}
@Override
public String getSegmentValue(final boolean includeFilters) {
fail();
return null;
}
@Override
public String toString(final boolean includeFilters) {
fail();
return null;
}
@Override
public UriResourceKind getKind() {
return UriResourceKind.navigationProperty;
}
@Override
public String getSegmentValue() {
fail();
return null;
}
@Override
public EdmNavigationProperty getProperty() {
return property;
}
@Override
public List<UriParameter> getKeyPredicates() {
fail();
return null;
}
@Override
public EdmType getTypeFilterOnCollection() {
return null;
}
@Override
public EdmType getTypeFilterOnEntry() {
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/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java | package com.sap.olingo.jpa.processor.core.util;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import jakarta.persistence.criteria.Root;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.junit.jupiter.api.BeforeEach;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractJoinQuery;
import com.sap.olingo.jpa.processor.core.query.JPAJoinQuery;
public class TestQueryBase extends TestBase {
protected JPAAbstractJoinQuery cut;
protected JPAEntityType jpaEntityType;
protected Root<?> root;
protected JPAODataSessionContextAccess context;
protected UriInfo uriInfo;
protected JPAODataInternalRequestContext requestContext;
protected JPAODataRequestContext externalContext;
protected OData odata;
public TestQueryBase() {
super();
}
@BeforeEach
protected void setup() throws ODataException, ODataJPAIllegalAccessException {
buildUriInfo("BusinessPartners", "BusinessPartner");
odata = mock(OData.class);
helper = new TestHelper(emf, PUNIT_NAME);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
jpaEntityType = helper.getJPAEntityType("BusinessPartners");
createHeaders();
context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages),
emf, dataSource, null, null, null);
externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
when(externalContext.getVersion()).thenReturn(JPAODataApiVersionAccess.DEFAULT_VERSION);
requestContext = new JPAODataInternalRequestContext(externalContext, context, odata);
requestContext.setUriInfo(uriInfo);
cut = new JPAJoinQuery(null, requestContext);
root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass());
joinTables = new HashMap<>();
joinTables.put(jpaEntityType.getExternalName(), root);
}
protected EdmType buildUriInfo(final String esName, final String etName) {
uriInfo = mock(UriInfo.class);
final EdmEntitySet odataEs = mock(EdmEntitySet.class);
final EdmEntityType odataType = mock(EdmEntityType.class);
final List<UriResource> resources = new ArrayList<>();
final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class);
when(uriInfo.getUriResourceParts()).thenReturn(resources);
when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(0));
when(esResource.getEntitySet()).thenReturn(odataEs);
when(esResource.getKind()).thenReturn(UriResourceKind.entitySet);
when(esResource.getType()).thenReturn(odataType);
when(odataEs.getName()).thenReturn(esName);
when(odataEs.getEntityType()).thenReturn(odataType);
when(odataType.getNamespace()).thenReturn(PUNIT_NAME);
when(odataType.getName()).thenReturn(etName);
resources.add(esResource);
return odataType;
}
protected EdmType buildRequestContext(final String esName, final String etName)
throws ODataJPAIllegalAccessException {
final EdmType odataType = buildUriInfo(esName, etName);
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(emf.createEntityManager());
requestContext = new JPAODataInternalRequestContext(externalContext, context, odata);
requestContext.setUriInfo(uriInfo);
return odataType;
}
} | 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/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
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.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.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.TopOption;
public class ExpandItemDouble implements ExpandItem {
private UriResourceNavigation target;
public ExpandItemDouble(final EdmEntityType navigationTargetEntity) {
target = new UriResourceNavigationDouble(navigationTargetEntity, new EdmNavigationPropertyDouble(
navigationTargetEntity.getName()));
}
@Override
public LevelsExpandOption getLevelsOption() {
return null;
}
@Override
public FilterOption getFilterOption() {
fail();
return null;
}
@Override
public SearchOption getSearchOption() {
fail();
return null;
}
@Override
public OrderByOption getOrderByOption() {
fail();
return null;
}
@Override
public SkipOption getSkipOption() {
fail();
return null;
}
@Override
public TopOption getTopOption() {
fail();
return null;
}
@Override
public CountOption getCountOption() {
fail();
return null;
}
@Override
public SelectOption getSelectOption() {
fail();
return null;
}
@Override
public ExpandOption getExpandOption() {
fail();
return null;
}
@Override
public UriInfoResource getResourcePath() {
return new UriInfoResourceDouble(target);
}
@Override
public boolean isStar() {
return false;
}
@Override
public boolean isRef() {
fail();
return false;
}
@Override
public EdmType getStartTypeFilter() {
fail();
return null;
}
@Override
public boolean hasCountPath() {
fail();
return false;
}
@Override
public ApplyOption getApplyOption() {
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/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHttpHandler;
import org.apache.olingo.server.api.debug.DefaultDebugSupport;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataBatchProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
public class IntegrationTestHelper {
public final HttpServletRequest request;
public final HttpServletResponse response;
private final ArgumentCaptor<Integer> captorStatus;
private final ArgumentCaptor<String> captorHeader;
private final ArgumentCaptor<String> captorHeaderValue;
public static final String URI_PREFIX = "http://localhost:8080/Test/Olingo.svc/";
public static final String PUNIT_NAME = "com.sap.olingo.jpa";
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath) throws IOException,
ODataException {
this(localEmf, null, urlPath, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final AnnotationProvider annotationsProvider) throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, null, null, null, null, annotationsProvider, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final ProcessorSqlPatternProvider sqlPattern) throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, null, null, null, null, null, sqlPattern);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final Map<String, List<String>> headers) throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, null, headers, null, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final JPAODataGroupProvider groups) throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, null, null, null, groups, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource dataSource, final String urlPath)
throws IOException, ODataException {
this(localEmf, dataSource, urlPath, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final StringBuffer requestBody)
throws IOException, ODataException {
this(localEmf, null, urlPath, requestBody, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource dataSource, final String urlPath,
final String functionPackage)
throws IOException, ODataException {
this(localEmf, dataSource, urlPath, null, functionPackage, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource dataSource, final String urlPath,
final StringBuffer requestBody)
throws IOException, ODataException {
this(localEmf, dataSource, urlPath, requestBody, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final JPAODataPagingProvider provider) throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, provider);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final JPAODataClaimsProvider claims)
throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, null, null, claims, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath,
final JPAODataPagingProvider provider, final JPAODataClaimsProvider claims) throws IOException, ODataException {
this(localEmf, null, urlPath, null, null, provider, null, claims, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory emf, final String urlPath,
final JPAODataPagingProvider provider, final Map<String, List<String>> headers) throws IOException,
ODataException {
this(emf, null, urlPath, null, null, provider, headers, null, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource dataSource, final String urlPath,
final StringBuffer requestBody,
final String functionPackage, final JPAODataPagingProvider provider) throws IOException, ODataException {
this(localEmf, dataSource, urlPath, requestBody, functionPackage, provider, null, null, null, null, null);
}
public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource dataSource, final String urlPath,
final StringBuffer requestBody, final String functionPackage, final JPAODataPagingProvider pagingProvider,
final Map<String, List<String>> headers, final JPAODataClaimsProvider claims, final JPAODataGroupProvider groups,
final AnnotationProvider annotationsProvider, final ProcessorSqlPatternProvider sqlPattern)
throws IOException, ODataException {
super();
final OData odata = OData.newInstance();
String[] packages = TestBase.enumPackages;
captorStatus = ArgumentCaptor.forClass(Integer.class);
captorHeader = ArgumentCaptor.forClass(String.class);
captorHeaderValue = ArgumentCaptor.forClass(String.class);
this.request = getRequestMock(URI_PREFIX + urlPath,
requestBody == null ? null : new StringBuilder(requestBody.toString()), headers);
this.response = getResponseMock();
if (functionPackage != null)
packages = ArrayUtils.add(packages, functionPackage);
final JPAEdmProvider edmProvider = buildEdmProvider(localEmf, annotationsProvider, packages);
final JPAODataSessionContextAccess sessionContext = new JPAODataContextAccessDouble(edmProvider, localEmf,
dataSource, pagingProvider, annotationsProvider, sqlPattern, functionPackage);
final ODataHttpHandler handler = odata.createHandler(odata.createServiceMetadata(sessionContext
.getApiVersion(JPAODataApiVersionAccess.DEFAULT_VERSION)
.getEdmProvider(),
new ArrayList<>()));
final JPAODataInternalRequestContext requestContext = buildRequestContext(localEmf, claims, groups, edmProvider,
sessionContext, odata);
handler.register(new JPAODataRequestProcessor(sessionContext, requestContext));
handler.register(new JPAODataBatchProcessor(sessionContext, requestContext));
handler.process(request, response);
}
public JPAODataInternalRequestContext buildRequestContext(final EntityManagerFactory localEmf,
final JPAODataClaimsProvider claims, final JPAODataGroupProvider groups, final JPAEdmProvider edmProvider,
final JPAODataSessionContextAccess sessionContext, final OData odata) throws ODataException {
final EntityManager em = createEmfWrapper(localEmf, edmProvider,
sessionContext.getSqlPatternProvider() != null ? sessionContext.getSqlPatternProvider() : null)
.createEntityManager();
final JPAODataRequestContext externalContext = mock(JPAODataRequestContext.class);
when(externalContext.getEntityManager()).thenReturn(em);
when(externalContext.getClaimsProvider()).thenReturn(Optional.ofNullable(claims));
when(externalContext.getGroupsProvider()).thenReturn(Optional.ofNullable(groups));
when(externalContext.getDebuggerSupport()).thenReturn(new DefaultDebugSupport());
when(externalContext.getRequestParameter()).thenReturn(mock(JPARequestParameterMap.class));
return new JPAODataInternalRequestContext(externalContext, sessionContext, odata);
}
public JPAEdmProvider buildEdmProvider(final EntityManagerFactory localEmf,
final AnnotationProvider annotationsProvider, final String[] packages) throws ODataException {
return new JPAEdmProvider(PUNIT_NAME, localEmf, null, packages,
annotationsProvider == null ? Collections.emptyList() : Collections.singletonList(annotationsProvider));
}
public HttpServletResponse getResponse() {
return response;
}
public int getStatus() {
verify(response).setStatus(captorStatus.capture());
return captorStatus.getValue();
}
public String getHeader(final String name) {
verify(response, atLeastOnce()).addHeader(captorHeader.capture(), captorHeaderValue.capture());
final var index = captorHeader.getAllValues().indexOf(name);
if (index >= 0)
return captorHeaderValue.getAllValues().get(index);
return null;
}
public String getRawResult() throws IOException {
final InputStream in = asInputStream();
final StringBuilder builder = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String read;
while ((read = reader.readLine()) != null) {
builder.append(read);
}
reader.close();
return builder.toString();
}
public List<String> getRawBatchResult() throws IOException {
final List<String> result = new ArrayList<>();
final InputStream in = asInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String read;
while ((read = reader.readLine()) != null) {
result.add(read);
}
reader.close();
return result;
}
public InputStream asInputStream() throws IOException {
return new ResultStream((OutPutStream) response.getOutputStream());
}
public ArrayNode getValues() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(getRawResult());
if (!(node.get("value") instanceof ArrayNode))
fail("Wrong result type; ArrayNode expected");
return (ArrayNode) node.get("value");
}
public ObjectNode getValue() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode value = mapper.readTree(getRawResult());
if (!(value instanceof ObjectNode))
fail("Wrong result type; ObjectNode expected");
return (ObjectNode) value;
}
public ValueNode getSingleValue() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode value = mapper.readTree(getRawResult());
if (!(value instanceof ValueNode))
fail("Wrong result type; ValueNode expected");
return (ValueNode) value;
}
public ValueNode getSingleValue(final String nodeName) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(getRawResult());
if (!(node.get(nodeName) instanceof ValueNode))
fail("Wrong result type; ArrayNode expected");
return (ValueNode) node.get(nodeName);
}
public void assertStatus(final int exp) throws IOException {
assertEquals(exp, getStatus(), getRawResult());
}
public int getBatchResultStatus(final int i) throws IOException {
final List<String> result = getRawBatchResult();
int count = 0;
for (final String resultLine : result) {
if (resultLine.contains("HTTP/1.1")) {
count += 1;
if (count == i) {
final String[] statusElements = resultLine.split(" ");
return Integer.parseInt(statusElements[1]);
}
}
}
return 0;
}
public JsonNode getBatchResult(final int i) throws IOException {
final List<String> result = getRawBatchResult();
int count = 0;
boolean found = false;
for (final String resultLine : result) {
if (resultLine.contains("HTTP/1.1")) {
count += 1;
if (count == i) {
found = true;
}
}
if (found && resultLine.startsWith("{")) {
final ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(resultLine);
}
}
return null;
}
public byte[] getBinaryResult() throws IOException {
final InputStream in = asInputStream();
final byte[] result = new byte[((ResultStream) in).getSize()];
in.read(result);
return result;
}
public static HttpServletRequest getRequestMock(final String uri) throws IOException {
return getRequestMock(uri, null);
}
public static HttpServletRequest getRequestMock(final String uri, final StringBuilder body) throws IOException {
return getRequestMock(uri, body, Collections.emptyMap());
}
public static HttpServletRequest getRequestMock(final String uri, final StringBuilder body,
final Map<String, List<String>> headers) throws IOException {
final HttpRequestHeaderDouble requestHeader = new HttpRequestHeaderDouble();
final HttpServletRequest response = mock(HttpServletRequest.class);
final String[] uriParts = uri.split("\\?");
requestHeader.setHeaders(headers);
if (uri.contains("$batch")) {
when(response.getMethod()).thenReturn(HttpMethod.POST.toString());
requestHeader.setBatchRequest();
} else {
when(response.getMethod()).thenReturn(HttpMethod.GET.toString());
}
when(response.getInputStream()).thenReturn(new ServletInputStreamDouble(body));
when(response.getProtocol()).thenReturn("HTTP/1.1");
when(response.getServletPath()).thenReturn("/Olingo.svc");
when(response.getQueryString()).thenReturn((uriParts.length == 2) ? uriParts[1] : null);
when(response.getRequestURL()).thenReturn(new StringBuffer(uriParts[0]));
when(response.getHeaderNames()).thenReturn(requestHeader.getEnumerator());
final Enumeration<String> headerEnumerator = requestHeader.getEnumerator();
while (headerEnumerator.hasMoreElements()) {
final String header = headerEnumerator.nextElement();
when(response.getHeaders(header)).thenReturn(requestHeader.get(header));
}
return response;
}
public static HttpServletResponse getResponseMock() throws IOException {
final HttpServletResponse response = mock(HttpServletResponse.class, Answers.RETURNS_MOCKS);
when(response.getOutputStream()).thenReturn(new OutPutStream());
return response;
}
@SuppressWarnings("unchecked")
private EntityManagerFactory createEmfWrapper(@Nonnull final EntityManagerFactory emf,
@Nonnull final JPAEdmProvider jpaEdm, final ProcessorSqlPatternProvider sqlPattern) throws ODataException {
try {
final Class<? extends EntityManagerFactory> wrapperClass = (Class<? extends EntityManagerFactory>) Class
.forName("com.sap.olingo.jpa.processor.cb.api.EntityManagerFactoryWrapper");
try {
return wrapperClass.getConstructor(EntityManagerFactory.class, JPAServiceDocument.class,
ProcessorSqlPatternProvider.class).newInstance(emf, jpaEdm.getServiceDocument(), sqlPattern);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new ODataException(e.getMessage());
}
} catch (final ClassNotFoundException e) {
return emf;
}
}
public static class OutPutStream extends ServletOutputStream {
List<Integer> buffer = new ArrayList<>();
@Override
public void write(final int nextByte) throws IOException {
buffer.add(nextByte);
}
public Iterator<Integer> getBuffer() {
return buffer.iterator();
}
public int getSize() {
return buffer.size();
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(final WriteListener writeListener) {
// Not yet needed
}
}
//
public static class ResultStream extends InputStream {
private final Iterator<Integer> bufferExcess;
private final int size;
public ResultStream(final OutPutStream buffer) {
super();
this.bufferExcess = buffer.getBuffer();
this.size = buffer.getSize();
}
@Override
public int read() throws IOException {
if (bufferExcess.hasNext())
return bufferExcess.next();
return -1;
}
public int getSize() {
return size;
}
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/SelectOptionDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/SelectOptionDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
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.SystemQueryOptionKind;
public class SelectOptionDouble implements SelectOption {
protected static final String SELECT_ITEM_SEPARATOR = ",";
protected static final String SELECT_ALL = "*";
protected static final String SELECT_PATH_SEPARATOR = "/";
private final String text;
private final List<SelectItem> selItems;
public SelectOptionDouble(String text) {
super();
this.text = text;
this.selItems = new ArrayList<>();
parseText();
}
@Override
public SystemQueryOptionKind getKind() {
return SystemQueryOptionKind.SELECT;
}
@Override
public String getName() {
return null;
}
@Override
public List<SelectItem> getSelectItems() {
return Collections.unmodifiableList(selItems);
}
@Override
public String getText() {
return text;
}
private void parseText() {
if (SELECT_ALL.equals(text)) {
final SelectItem item = mock(SelectItem.class);
when(item.isStar()).thenReturn(true);
selItems.add(item);
} else {
final String[] selectList = text.split(SELECT_ITEM_SEPARATOR);
for (String elementText : selectList) {
final List<UriResource> uriResources = new ArrayList<>();
final UriInfoResource resource = mock(UriInfoResource.class);
final SelectItem item = mock(SelectItem.class);
when(resource.getUriResourceParts()).thenReturn(uriResources);
when(item.isStar()).thenReturn(false);
when(item.getResourcePath()).thenReturn(resource);
selItems.add(item);
String[] elements = elementText.split(SELECT_PATH_SEPARATOR);
for (String element : elements) {
final UriResourceProperty property = mock(UriResourceProperty.class);
when(property.getSegmentValue()).thenReturn(element);
uriResources.add(property);
}
}
}
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceProperty;
public class UriResourcePropertyDouble implements UriResourceProperty {
private final EdmProperty property;
public UriResourcePropertyDouble(EdmProperty property) {
super();
this.property = property;
}
@Override
public EdmType getType() {
fail();
return null;
}
@Override
public boolean isCollection() {
return false;
}
@Override
public String getSegmentValue(boolean includeFilters) {
fail();
return null;
}
@Override
public String toString(boolean includeFilters) {
fail();
return null;
}
@Override
public UriResourceKind getKind() {
fail();
return null;
}
@Override
public String getSegmentValue() {
fail();
return null;
}
@Override
public EdmProperty getProperty() {
return property;
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.edm.EdmMapping;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmTerm;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.geo.SRID;
public class EdmPropertyDouble implements EdmProperty {
private final String name;
public EdmPropertyDouble(final String name) {
super();
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public EdmType getType() {
fail();
return null;
}
@Override
public boolean isCollection() {
fail();
return false;
}
@Override
public EdmMapping getMapping() {
fail();
return null;
}
@Override
public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) {
fail();
return null;
}
@Override
public List<EdmAnnotation> getAnnotations() {
fail();
return null;
}
@Override
public String getMimeType() {
fail();
return null;
}
@Override
public boolean isPrimitive() {
fail();
return false;
}
@Override
public boolean isNullable() {
fail();
return false;
}
@Override
public Integer getMaxLength() {
fail();
return null;
}
@Override
public Integer getPrecision() {
fail();
return null;
}
@Override
public Integer getScale() {
fail();
return null;
}
@Override
public SRID getSrid() {
fail();
return null;
}
@Override
public boolean isUnicode() {
fail();
return false;
}
@Override
public String getDefaultValue() {
fail();
return null;
}
@Override
public EdmType getTypeWithAnnotations() {
fail();
return null;
}
@Override
public String getScaleAsString() {
fail();
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/test/java/com/sap/olingo/jpa/processor/core/util/CountQueryMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/CountQueryMatcher.java | package com.sap.olingo.jpa.processor.core.util;
import org.apache.olingo.server.api.ODataApplicationException;
import org.mockito.ArgumentMatcher;
import com.sap.olingo.jpa.processor.core.query.JPACountQuery;
public class CountQueryMatcher implements ArgumentMatcher<JPACountQuery> {
private final long extCountResult;
private boolean executed = false;
public CountQueryMatcher(long exp) {
extCountResult = exp;
}
@Override
public boolean matches(JPACountQuery query) {
if (query != null) {
if (extCountResult != 0 && !executed) {
try {
executed = true; // Query can be used only once but matcher is called twice
return extCountResult == query.countResults();
} catch (ODataApplicationException e) {
System.out.print(e.getMessage());
return false;
}
}
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/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import java.util.Map;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.server.api.deserializer.DeserializerException;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.uri.UriHelper;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
public class UriHelperDouble implements UriHelper {
private Map<String, String> keyPredicates;
private String idPropertyName;
@Override
public String buildContextURLSelectList(EdmStructuredType type, ExpandOption expand, SelectOption select)
throws SerializerException {
fail();
return null;
}
@Override
public String buildContextURLKeyPredicate(List<UriParameter> keys) throws SerializerException {
fail();
return null;
}
@Override
public String buildCanonicalURL(EdmEntitySet edmEntitySet, Entity entity) throws SerializerException {
fail();
return null;
}
@Override
public String buildKeyPredicate(EdmEntityType edmEntityType, Entity entity) throws SerializerException {
return keyPredicates.get(entity.getProperty(idPropertyName).getValue());
}
@Override
public UriResourceEntitySet parseEntityId(Edm edm, String entityId, String rawServiceRoot)
throws DeserializerException {
fail();
return null;
}
public Map<String, String> getKeyPredicates() {
return keyPredicates;
}
public void setKeyPredicates(Map<String, String> keyPredicates, String idPropertyName) {
this.keyPredicates = keyPredicates;
this.idPropertyName = idPropertyName;
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/TestHelper.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestHelper.java | package com.sap.olingo.jpa.processor.core.util;
import java.lang.reflect.AnnotatedElement;
import java.util.Optional;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.ManagedType;
import jakarta.persistence.metamodel.Metamodel;
import jakarta.persistence.metamodel.SingularAttribute;
import org.apache.olingo.commons.api.ex.ODataException;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctions;
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.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
public class TestHelper {
private final Metamodel jpaMetamodel;
public final JPAServiceDocument sd;
public final JPAEdmProvider edmProvider;
public TestHelper(final EntityManagerFactory emf, final String namespace) throws ODataException {
this.jpaMetamodel = emf.getMetamodel();
edmProvider = new JPAEdmProvider(namespace, emf, null, TestBase.enumPackages);
sd = edmProvider.getServiceDocument();
sd.getEdmEntityContainer();
}
public EntityType<?> getEntityType(final Class<?> clazz) {
for (final EntityType<?> entityType : jpaMetamodel.getEntities()) {
if (entityType.getJavaType() == clazz) {
return entityType;
}
}
return null;
}
public JPAEntityType getJPAEntityType(final String entitySetName) throws ODataJPAModelException {
return sd.getEntity(entitySetName);
}
public JPAEntityType getJPAEntityType(final Class<?> clazz) throws ODataJPAModelException {
return sd.getEntity(clazz);
}
public JPAAssociationPath getJPAAssociationPath(final String entitySetName, final String attributeExternalName)
throws ODataJPAModelException {
final JPAEntityType jpaEntity = sd.getEntity(entitySetName);
return jpaEntity.getAssociationPath(attributeExternalName);
}
public JPAAssociationPath getJPAAssociationPath(final Class<?> clazz, final String attributeExternalName)
throws ODataJPAModelException {
final JPAEntityType jpaEntity = sd.getEntity(clazz);
return jpaEntity.getAssociationPath(attributeExternalName);
}
public JPAAttribute getJPAAssociation(final String entitySetName, final String attributeInternalName)
throws ODataJPAModelException {
final JPAEntityType jpaEntity = sd.getEntity(entitySetName);
return jpaEntity.getAssociation(attributeInternalName);
}
public Optional<JPAAttribute> getJPAAttribute(final String entitySetName, final String attributeInternalName)
throws ODataJPAModelException {
final JPAEntityType jpaEntity = sd.getEntity(entitySetName);
return jpaEntity.getAttribute(attributeInternalName);
}
public Optional<JPAAttribute> getJPAAttribute(final Class<?> clazz, final String attributeInternalName)
throws ODataJPAModelException {
final JPAEntityType jpaEntity = sd.getEntity(clazz);
return jpaEntity.getAttribute(attributeInternalName);
}
public EdmFunction getStoredProcedure(final EntityType<?> jpaEntityType, final String string) {
if (jpaEntityType.getJavaType() instanceof AnnotatedElement) {
final EdmFunctions jpaStoredProcedureList = jpaEntityType.getJavaType()
.getAnnotation(EdmFunctions.class);
if (jpaStoredProcedureList != null) {
for (final EdmFunction jpaStoredProcedure : jpaStoredProcedureList.value()) {
if (jpaStoredProcedure.name().equals(string)) return jpaStoredProcedure;
}
}
}
return null;
}
public Attribute<?, ?> getAttribute(final ManagedType<?> et, final String attributeName) {
for (final SingularAttribute<?, ?> attribute : et.getSingularAttributes()) {
if (attribute.getName().equals(attributeName))
return attribute;
}
return null;
}
public EmbeddableType<?> getEmbeddableType(final String typeName) {
for (final EmbeddableType<?> embeddableType : jpaMetamodel.getEmbeddables()) {
if (embeddableType.getJavaType().getSimpleName().equals(typeName)) {
return embeddableType;
}
}
return null;
}
public Attribute<?, ?> getDeclaredAttribute(final ManagedType<?> et, final String attributeName) {
for (final Attribute<?, ?> attribute : et.getDeclaredAttributes()) {
if (attribute.getName().equals(attributeName))
return attribute;
}
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/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.edm.EdmElement;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmTerm;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
public class EdmEntityTypeDouble implements EdmEntityType {
private final String name;
private final JPAEdmNameBuilder nameBuilder;
public EdmEntityTypeDouble(final JPAEdmNameBuilder nameBuilder, final String name) {
this.name = name;
this.nameBuilder = nameBuilder;
}
@Override
public EdmElement getProperty(final String name) {
fail();
return null;
}
@Override
public List<String> getPropertyNames() {
fail();
return null;
}
@Override
public EdmProperty getStructuralProperty(final String name) {
fail();
return null;
}
@Override
public EdmNavigationProperty getNavigationProperty(final String name) {
fail();
return null;
}
@Override
public List<String> getNavigationPropertyNames() {
fail();
return null;
}
@Override
public boolean compatibleTo(final EdmType targetType) {
fail();
return false;
}
@Override
public boolean isOpenType() {
fail();
return false;
}
@Override
public boolean isAbstract() {
fail();
return false;
}
@Override
public FullQualifiedName getFullQualifiedName() {
return new FullQualifiedName(nameBuilder.getNamespace(), name);
}
@Override
public String getNamespace() {
return nameBuilder.getNamespace();
}
@Override
public EdmTypeKind getKind() {
fail();
return null;
}
@Override
public String getName() {
return name;
}
@Override
public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) {
fail();
return null;
}
@Override
public List<EdmAnnotation> getAnnotations() {
fail();
return null;
}
@Override
public List<String> getKeyPredicateNames() {
fail();
return null;
}
@Override
public List<EdmKeyPropertyRef> getKeyPropertyRefs() {
fail();
return null;
}
@Override
public EdmKeyPropertyRef getKeyPropertyRef(final String keyPredicateName) {
fail();
return null;
}
@Override
public boolean hasStream() {
fail();
return false;
}
@Override
public EdmEntityType getBaseType() {
fail();
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/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
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.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmMapping;
import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding;
import org.apache.olingo.commons.api.edm.EdmTerm;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
public class EdmEntitySetDouble implements EdmEntitySet {
private final String name;
private final EdmEntityType type;
// private final JPAEdmNameBuilder nameBuilder;
public EdmEntitySetDouble(final JPAEdmNameBuilder nameBuilder, final String name) {
super();
this.name = name;
this.type = new EdmEntityTypeDouble(nameBuilder, name.substring(0, name.length() - 1));
// this.nameBuilder = nameBuilder;
}
@Override
public String getTitle() {
return null;
}
@Override
public EdmBindingTarget getRelatedBindingTarget(final String path) {
return null;
}
@Override
public List<EdmNavigationPropertyBinding> getNavigationPropertyBindings() {
return null;
}
@Override
public EdmEntityContainer getEntityContainer() {
return null;
}
@Override
public EdmEntityType getEntityType() {
return type;
}
@Override
public String getName() {
return name;
}
@Override
public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) {
return null;
}
@Override
public List<EdmAnnotation> getAnnotations() {
return null;
}
@Override
public boolean isIncludeInServiceDocument() {
return false;
}
@Override
public EdmMapping getMapping() {
fail();
return null;
}
@Override
public EdmEntityType getEntityTypeWithAnnotations() {
fail();
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/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java | package com.sap.olingo.jpa.processor.core.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Root;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
public class TestBase {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
public static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" };
protected static EntityManagerFactory emf;
protected TestHelper helper;
protected Map<String, List<String>> headers;
protected static JPAEdmNameBuilder nameBuilder;
protected static DataSource dataSource;
protected HashMap<String, From<?, ?>> joinTables;
@BeforeAll
public static void setupClass() {
dataSource = DataSourceHelper.createDataSource(DataSourceHelper.DB_H2);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, dataSource);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
}
protected void createHeaders() {
headers = new HashMap<>();
final List<String> languageHeaders = new ArrayList<>();
languageHeaders.add("de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
headers.put("accept-language", languageHeaders);
}
protected void addHeader(final String header, final String value) {
final List<String> newHeader = new ArrayList<>();
newHeader.add(value);
headers.put(header, newHeader);
}
protected TestHelper getHelper() throws ODataException {
if (helper == null)
helper = new TestHelper(emf, PUNIT_NAME);
return helper;
}
protected void fillJoinTable(final Root<?> joinRoot) {
Join<?, ?> join = joinRoot.join("locationName", JoinType.LEFT);
joinTables.put("LocationName", join);
join = joinRoot.join("address", JoinType.LEFT);
join = join.join("countryName", JoinType.LEFT);
joinTables.put("Address/CountryName", join);
join = joinRoot.join("address", JoinType.LEFT);
join = join.join("regionName", JoinType.LEFT);
joinTables.put("Address/RegionName", join);
}
} | 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/test/java/com/sap/olingo/jpa/processor/core/util/AbstractWatchDogTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/AbstractWatchDogTest.java | package com.sap.olingo.jpa.processor.core.util;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection;
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.edm.provider.annotation.CsdlNavigationPropertyPath;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyValue;
public abstract class AbstractWatchDogTest {
protected static CsdlPropertyValue createConstantsExpression(final String property, final String value) {
final CsdlConstantExpression expandable = mock(CsdlConstantExpression.class);
final CsdlPropertyValue expandableValue = mock(CsdlPropertyValue.class);
when(expandableValue.getProperty()).thenReturn(property);
when(expandableValue.getValue()).thenReturn(expandable);
when(expandable.asConstant()).thenReturn(expandable);
when(expandable.getValue()).thenReturn(value);
return expandableValue;
}
protected static CsdlPropertyValue createCollectionExpression(final String property,
final List<CsdlExpression> collection) {
final CsdlPropertyValue value = mock(CsdlPropertyValue.class);
final CsdlCollection ascendingOnlyCollection = mock(CsdlCollection.class);
when(value.getProperty()).thenReturn(property);
when(value.getValue()).thenReturn(ascendingOnlyCollection);
when(ascendingOnlyCollection.getItems()).thenReturn(collection);
when(ascendingOnlyCollection.asDynamic()).thenReturn(ascendingOnlyCollection);
when(ascendingOnlyCollection.asCollection()).thenReturn(ascendingOnlyCollection);
return value;
}
protected static CsdlNavigationPropertyPath createAnnotationNavigationPath(final String pathString) {
final CsdlNavigationPropertyPath path = mock(CsdlNavigationPropertyPath.class);
when(path.asNavigationPropertyPath()).thenReturn(path);
when(path.asDynamic()).thenReturn(path);
when(path.getValue()).thenReturn(pathString);
return path;
}
protected static List<CsdlExpression> asExpression(final String[] paths) {
return asExpression(Arrays.asList(paths));
}
protected static List<CsdlExpression> asExpression(final List<String> paths) {
return paths
.stream()
.map(string -> createAnnotationNavigationPath(string))
.map(path -> (CsdlExpression) path)
.toList();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmAction;
import org.apache.olingo.commons.api.edm.EdmAnnotations;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmEnumType;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmSchema;
import org.apache.olingo.commons.api.edm.EdmTerm;
import org.apache.olingo.commons.api.edm.EdmTypeDefinition;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.etag.ServiceMetadataETagSupport;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
public class ServiceMetadataDouble implements ServiceMetadata {
private final Edm edm;
public ServiceMetadataDouble() {
super();
edm = new EdmDouble();
}
public ServiceMetadataDouble(JPAEdmNameBuilder nameBuilder, String typeName) {
super();
this.nameBuilder = nameBuilder;
this.edm = new EdmDouble(typeName);
}
private JPAEdmNameBuilder nameBuilder;
@Override
public Edm getEdm() {
return edm;
}
@Override
public ODataServiceVersion getDataServiceVersion() {
fail();
return null;
}
@Override
public List<EdmxReference> getReferences() {
fail();
return null;
}
@Override
public ServiceMetadataETagSupport getServiceMetadataETagSupport() {
fail();
return null;
}
class EdmDouble implements Edm {
private Map<FullQualifiedName, EdmEntityType> typeMap;
public EdmDouble() {
super();
typeMap = new HashMap<>();
}
public EdmDouble(String name) {
super();
typeMap = new HashMap<>();
EdmEntityType edmType = new EdmEntityTypeDouble(nameBuilder, name);
typeMap.put(edmType.getFullQualifiedName(), edmType);
}
@Override
public List<EdmSchema> getSchemas() {
fail();
return null;
}
@Override
public EdmSchema getSchema(String namespace) {
fail();
return null;
}
@Override
public EdmEntityContainer getEntityContainer() {
fail();
return null;
}
@Override
public EdmEntityContainer getEntityContainer(FullQualifiedName name) {
fail();
return null;
}
@Override
public EdmEnumType getEnumType(FullQualifiedName name) {
fail();
return null;
}
@Override
public EdmTypeDefinition getTypeDefinition(FullQualifiedName name) {
fail();
return null;
}
@Override
public EdmEntityType getEntityType(FullQualifiedName name) {
return typeMap.get(name);
}
@Override
public EdmComplexType getComplexType(FullQualifiedName name) {
fail();
return null;
}
@Override
public EdmAction getUnboundAction(FullQualifiedName actionName) {
fail();
return null;
}
@Override
public EdmAction getBoundAction(FullQualifiedName actionName, FullQualifiedName bindingParameterTypeName,
Boolean isBindingParameterCollection) {
fail();
return null;
}
@Override
public List<EdmFunction> getUnboundFunctions(FullQualifiedName functionName) {
fail();
return null;
}
@Override
public EdmFunction getUnboundFunction(FullQualifiedName functionName, List<String> parameterNames) {
fail();
return null;
}
@Override
public EdmFunction getBoundFunction(FullQualifiedName functionName, FullQualifiedName bindingParameterTypeName,
Boolean isBindingParameterCollection, List<String> parameterNames) {
fail();
return null;
}
@Override
public EdmTerm getTerm(FullQualifiedName termName) {
fail();
return null;
}
@Override
public EdmAnnotations getAnnotationGroup(FullQualifiedName targetName, String qualifier) {
fail();
return null;
}
@Override
public EdmAction getBoundActionWithBindingType(FullQualifiedName bindingParameterTypeName,
Boolean isBindingParameterCollection) {
return null;
}
@Override
public List<EdmFunction> getBoundFunctionsWithBindingType(FullQualifiedName bindingParameterTypeName,
Boolean isBindingParameterCollection) {
fail();
return null;
}
@Override
public EdmComplexType getComplexTypeWithAnnotations(FullQualifiedName arg0) {
fail();
return null;
}
@Override
public EdmEntityType getEntityTypeWithAnnotations(FullQualifiedName arg0) {
fail();
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/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmOnDelete;
import org.apache.olingo.commons.api.edm.EdmReferentialConstraint;
import org.apache.olingo.commons.api.edm.EdmTerm;
public class EdmNavigationPropertyDouble implements EdmNavigationProperty {
private final String name;
public EdmNavigationPropertyDouble(final String name) {
super();
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isCollection() {
fail();
return false;
}
@Override
public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) {
fail();
return null;
}
@Override
public List<EdmAnnotation> getAnnotations() {
fail();
return null;
}
@Override
public EdmEntityType getType() {
fail();
return null;
}
@Override
public boolean isNullable() {
fail();
return false;
}
@Override
public boolean containsTarget() {
fail();
return false;
}
@Override
public EdmNavigationProperty getPartner() {
fail();
return null;
}
@Override
public String getReferencingPropertyName(final String referencedPropertyName) {
fail();
return null;
}
@Override
public List<EdmReferentialConstraint> getReferentialConstraints() {
fail();
return null;
}
@Override
public EdmOnDelete getOnDelete() {
fail();
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/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.List;
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.SystemQueryOptionKind;
public class ExpandOptionDouble implements ExpandOption {
private final String text;
private final List<ExpandItem> items;
public ExpandOptionDouble(final String text, final List<ExpandItem> items) {
super();
this.text = text;
this.items = items;
}
@Override
public SystemQueryOptionKind getKind() {
fail();
return null;
}
@Override
public String getName() {
fail();
return null;
}
@Override
public String getText() {
return text;
}
@Override
public List<ExpandItem> getExpandItems() {
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/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoAll;
import org.apache.olingo.server.api.uri.UriInfoBatch;
import org.apache.olingo.server.api.uri.UriInfoCrossjoin;
import org.apache.olingo.server.api.uri.UriInfoEntityId;
import org.apache.olingo.server.api.uri.UriInfoKind;
import org.apache.olingo.server.api.uri.UriInfoMetadata;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriInfoService;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.queryoption.AliasQueryOption;
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.SystemQueryOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
public class UriInfoDouble implements UriInfo {
private final SelectOption selOpts;
private ExpandOption expandOpts;
private List<UriResource> uriResources;
public UriInfoDouble(final SelectOption selOpts) {
super();
this.selOpts = selOpts;
this.uriResources = new ArrayList<>(0);
}
public UriInfoDouble(final UriInfoResource resourcePath) {
super();
this.selOpts = null;
this.uriResources = resourcePath.getUriResourceParts();
}
@Override
public FormatOption getFormatOption() {
fail();
return null;
}
@Override
public String getFragment() {
fail();
return null;
}
@Override
public List<CustomQueryOption> getCustomQueryOptions() {
fail();
return null;
}
@Override
public ExpandOption getExpandOption() {
return expandOpts;
}
@Override
public FilterOption getFilterOption() {
fail();
return null;
}
@Override
public IdOption getIdOption() {
fail();
return null;
}
@Override
public CountOption getCountOption() {
fail();
return null;
}
@Override
public OrderByOption getOrderByOption() {
fail();
return null;
}
@Override
public SearchOption getSearchOption() {
fail();
return null;
}
@Override
public SelectOption getSelectOption() {
return selOpts;
}
@Override
public SkipOption getSkipOption() {
fail();
return null;
}
@Override
public SkipTokenOption getSkipTokenOption() {
fail();
return null;
}
@Override
public TopOption getTopOption() {
fail();
return null;
}
@Override
public List<UriResource> getUriResourceParts() {
return uriResources;
}
@Override
public String getValueForAlias(String alias) {
fail();
return null;
}
@Override
public List<String> getEntitySetNames() {
fail();
return null;
}
@Override
public EdmEntityType getEntityTypeCast() {
fail();
return null;
}
@Override
public UriInfoKind getKind() {
fail();
return null;
}
@Override
public UriInfoService asUriInfoService() {
fail();
return null;
}
@Override
public UriInfoAll asUriInfoAll() {
fail();
return null;
}
@Override
public UriInfoBatch asUriInfoBatch() {
fail();
return null;
}
@Override
public UriInfoCrossjoin asUriInfoCrossjoin() {
fail();
return null;
}
@Override
public UriInfoEntityId asUriInfoEntityId() {
fail();
return null;
}
@Override
public UriInfoMetadata asUriInfoMetadata() {
fail();
return null;
}
@Override
public UriInfoResource asUriInfoResource() {
fail();
return null;
}
@Override
public List<SystemQueryOption> getSystemQueryOptions() {
fail();
return null;
}
@Override
public List<AliasQueryOption> getAliases() {
fail();
return null;
}
class primitiveDouble implements UriResourcePrimitiveProperty {
@Override
public EdmProperty getProperty() {
fail();
return null;
}
@Override
public EdmType getType() {
fail();
return null;
}
@Override
public boolean isCollection() {
fail();
return false;
}
@Override
public String getSegmentValue(boolean includeFilters) {
fail();
return null;
}
@Override
public String toString(boolean includeFilters) {
fail();
return null;
}
@Override
public UriResourceKind getKind() {
fail();
return null;
}
@Override
public String getSegmentValue() {
fail();
return null;
}
}
class complexDouble implements UriResourceComplexProperty {
@Override
public EdmProperty getProperty() {
fail();
return null;
}
@Override
public EdmType getType() {
fail();
return null;
}
@Override
public boolean isCollection() {
fail();
return false;
}
@Override
public String getSegmentValue(boolean includeFilters) {
fail();
return null;
}
@Override
public String toString(boolean includeFilters) {
fail();
return null;
}
@Override
public UriResourceKind getKind() {
fail();
return null;
}
@Override
public String getSegmentValue() {
fail();
return null;
}
@Override
public EdmComplexType getComplexType() {
fail();
return null;
}
@Override
public EdmComplexType getComplexTypeFilter() {
fail();
return null;
}
}
class propertyDouble implements UriResourceProperty {
@Override
public EdmType getType() {
fail();
return null;
}
@Override
public boolean isCollection() {
fail();
return false;
}
@Override
public String getSegmentValue(boolean includeFilters) {
fail();
return null;
}
@Override
public String toString(boolean includeFilters) {
fail();
return null;
}
@Override
public UriResourceKind getKind() {
fail();
return null;
}
@Override
public String getSegmentValue() {
fail();
return null;
}
@Override
public EdmProperty getProperty() {
fail();
return null;
}
}
public void setExpandOpts(ExpandOption expandOpts) {
this.expandOpts = expandOpts;
}
public void setUriResources(List<UriResource> uriResources) {
this.uriResources = uriResources;
}
@Override
public ApplyOption getApplyOption() {
return null;
}
@Override
public DeltaTokenOption getDeltaTokenOption() {
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/test/java/com/sap/olingo/jpa/processor/core/util/TupleElementDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TupleElementDouble.java | package com.sap.olingo.jpa.processor.core.util;
import jakarta.persistence.TupleElement;
public class TupleElementDouble implements TupleElement<Object> {
// alias
private final String alias;
private final Object value;
public TupleElementDouble(final String alias, final Object value) {
super();
this.alias = alias;
this.value = value;
}
@Override
public String getAlias() {
return alias;
}
@Override
public Class<? extends Object> getJavaType() {
return value.getClass();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
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;
public class UriInfoResourceDouble implements UriInfoResource {
private final List<UriResource> resources;
public UriInfoResourceDouble(UriResourceNavigation target) {
resources = new ArrayList<>();
resources.add(target);
}
@Override
public List<CustomQueryOption> getCustomQueryOptions() {
fail();
return null;
}
@Override
public ExpandOption getExpandOption() {
fail();
return null;
}
@Override
public FilterOption getFilterOption() {
return null;
}
@Override
public FormatOption getFormatOption() {
fail();
return null;
}
@Override
public IdOption getIdOption() {
fail();
return null;
}
@Override
public CountOption getCountOption() {
fail();
return null;
}
@Override
public OrderByOption getOrderByOption() {
fail();
return null;
}
@Override
public SearchOption getSearchOption() {
fail();
return null;
}
@Override
public SelectOption getSelectOption() {
fail();
return null;
}
@Override
public SkipOption getSkipOption() {
fail();
return null;
}
@Override
public SkipTokenOption getSkipTokenOption() {
fail();
return null;
}
@Override
public TopOption getTopOption() {
fail();
return null;
}
@Override
public List<UriResource> getUriResourceParts() {
return resources;
}
@Override
public String getValueForAlias(String alias) {
fail();
return null;
}
@Override
public ApplyOption getApplyOption() {
return null;
}
@Override
public DeltaTokenOption getDeltaTokenOption() {
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/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java | package com.sap.olingo.jpa.processor.core.util;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.server.api.uri.UriResourceProperty;
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.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEtagValidator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAInheritanceInformation;
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.JPAQueryExtension;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
public class JPAEntityTypeDouble implements JPAEntityType {
private final JPAEntityType base;
public JPAEntityTypeDouble(final JPAEntityType base) {
super();
this.base = base;
}
@Override
public JPAAssociationAttribute getAssociation(final String internalName) throws ODataJPAModelException {
return base.getAssociation(internalName);
}
@Override
public JPAAssociationPath getAssociationPath(final String externalName) throws ODataJPAModelException {
return base.getAssociationPath(externalName);
}
@SuppressWarnings("unchecked")
@Override
public List<JPAAssociationPath> getAssociationPathList() throws ODataJPAModelException {
return (List<JPAAssociationPath>) failWithNull();
}
@Override
public Optional<JPAAttribute> getAttribute(final UriResourceProperty uriResourceItem) throws ODataJPAModelException {
fail();
return Optional.empty();
}
@Override
public Optional<JPAAttribute> getAttribute(final String internalName) throws ODataJPAModelException {
return base.getAttribute(internalName);
}
@Override
public Optional<JPAAttribute> getAttribute(final String internalName, final boolean respectIgnore)
throws ODataJPAModelException {
return base.getAttribute(internalName, respectIgnore);
}
@Override
public List<JPAAttribute> getAttributes() throws ODataJPAModelException {
return base.getAttributes();
}
@Override
public List<JPAPath> getCollectionAttributesPath() throws ODataJPAModelException {
fail();
return Collections.emptyList();
}
@Override
public List<JPAAssociationAttribute> getDeclaredAssociations() throws ODataJPAModelException {
fail();
return Collections.emptyList();
}
@Override
public List<JPAAttribute> getDeclaredAttributes() throws ODataJPAModelException {
return base.getDeclaredAttributes();
}
@Override
public Optional<JPAAttribute> getDeclaredAttribute(final String internalName) throws ODataJPAModelException {
return base.getDeclaredAttribute(internalName);
}
@Override
public List<JPACollectionAttribute> getDeclaredCollectionAttributes() throws ODataJPAModelException {
fail();
return Collections.emptyList();
}
@Override
public JPAPath getPath(final String externalName) throws ODataJPAModelException {
return base.getPath(externalName);
}
@Override
public JPAPath getPath(final String externalName, final boolean respectIgnore) throws ODataJPAModelException {
return (JPAPath) failWithNull();
}
@Override
public List<JPAPath> getPathList() throws ODataJPAModelException {
return base.getPathList();
}
@Override
public Class<?> getTypeClass() {
return base.getTypeClass();
}
@Override
public boolean isAbstract() {
return failWithFalse();
}
@Override
public FullQualifiedName getExternalFQN() {
return base.getExternalFQN();
}
@Override
public String getExternalName() {
return base.getExternalName();
}
@Override
public String getInternalName() {
return base.getInternalName();
}
@Override
public String getContentType() throws ODataJPAModelException {
return (String) failWithNull();
}
@Override
public JPAPath getContentTypeAttributePath() throws ODataJPAModelException {
return (JPAPath) failWithNull();
}
@SuppressWarnings("unchecked")
@Override
public List<JPAAttribute> getKey() throws ODataJPAModelException {
return (List<JPAAttribute>) failWithNull();
}
@SuppressWarnings("unchecked")
@Override
public List<JPAPath> getKeyPath() throws ODataJPAModelException {
return (List<JPAPath>) failWithNull();
}
@Override
public Class<?> getKeyType() {
return base.getKeyType();
}
@Override
public List<JPAPath> getSearchablePath() throws ODataJPAModelException {
return base.getSearchablePath();
}
@Override
public JPAPath getStreamAttributePath() throws ODataJPAModelException {
return base.getStreamAttributePath();
}
@Override
public String getTableName() {
return base.getTableName();
}
@Override
public boolean hasEtag() throws ODataJPAModelException {
return base.hasEtag();
}
@Override
public boolean hasStream() throws ODataJPAModelException {
return base.hasStream();
}
@Override
public List<JPAPath> searchChildPath(final JPAPath selectItemPath) throws ODataJPAModelException {
return base.searchChildPath(selectItemPath);
}
@Override
public JPACollectionAttribute getCollectionAttribute(final String externalName) throws ODataJPAModelException {
return base.getCollectionAttribute(externalName);
}
@Override
public List<JPAProtectionInfo> getProtections() throws ODataJPAModelException {
return base.getProtections();
}
@Override
public JPAPath getEtagPath() throws ODataJPAModelException {
return (JPAPath) failWithNull();
}
@Override
public boolean hasCompoundKey() {
return failWithFalse();
}
@Override
public boolean hasEmbeddedKey() {
return failWithFalse();
}
@Override
public <X extends EdmQueryExtensionProvider> Optional<JPAQueryExtension<X>> getQueryExtension()
throws ODataJPAModelException {
return Optional.empty();
}
@Override
public CsdlAnnotation getAnnotation(final String alias, final String term) throws ODataJPAModelException {
return this.base.getAnnotation(alias, term);
}
@Override
public JPAStructuredType getBaseType() throws ODataJPAModelException {
return base.getBaseType();
}
@Override
public JPAInheritanceInformation getInheritanceInformation() throws ODataJPAModelException {
fail();
return new JPAInheritanceInformation() {
@Override
public List<JPAOnConditionItem> getJoinColumnsList() throws ODataJPAModelException {
return List.of();
}
@Override
public List<JPAOnConditionItem> getReversedJoinColumnsList() throws ODataJPAModelException {
return List.of();
}
};
}
@Override
public Object getAnnotationValue(final String alias, final String term, final String property)
throws ODataJPAModelException {
return this.base.getAnnotationValue(alias, term, property);
}
@Override
public JPAEtagValidator getEtagValidator() {
fail();
return JPAEtagValidator.WEAK;
}
private Object failWithNull() {
fail();
return null;
}
private boolean failWithFalse() {
fail();
return false;
}
@Override
public List<String> getUserGroups() throws ODataJPAModelException {
fail();
return List.of();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/ComplexSerializerOptionsMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/ComplexSerializerOptionsMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import java.net.URI;
import org.apache.olingo.server.api.serializer.ComplexSerializerOptions;
public class ComplexSerializerOptionsMatcher extends SerializerOptionsMatcher<ComplexSerializerOptions> {
public ComplexSerializerOptionsMatcher(final String pattern) {
super(pattern);
}
@Override
protected URI getService(final ComplexSerializerOptions options) {
return options.getContextURL().getServiceRoot();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/InputStreamMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/InputStreamMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import java.io.IOException;
import java.io.InputStream;
import org.mockito.ArgumentMatcher;
public class InputStreamMatcher implements ArgumentMatcher<InputStream> {
private String extElement;
private String input = null;
public InputStreamMatcher(String pattern) {
extElement = pattern;
}
@Override
public boolean matches(final InputStream stream) {
if (stream != null) {
if (input == null) {
byte[] buffer = new byte[1024];
try {
stream.read(buffer);
} catch (IOException e) {
return false;
}
input = new String(buffer);
}
return input.contains(extElement);
}
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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/EntityCollectionSerializerOptionsMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/EntityCollectionSerializerOptionsMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import java.net.URI;
import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions;
public class EntityCollectionSerializerOptionsMatcher extends
SerializerOptionsMatcher<EntityCollectionSerializerOptions> {
public EntityCollectionSerializerOptionsMatcher(final String pattern) {
super(pattern);
}
@Override
protected URI getService(final EntityCollectionSerializerOptions options) {
return options.getContextURL().getServiceRoot();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/EntitySerializerOptionsMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/EntitySerializerOptionsMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import java.net.URI;
import org.apache.olingo.server.api.serializer.EntitySerializerOptions;
public class EntitySerializerOptionsMatcher extends SerializerOptionsMatcher<EntitySerializerOptions> {
public EntitySerializerOptionsMatcher(final String pattern) {
super(pattern);
}
@Override
protected URI getService(final EntitySerializerOptions options) {
return options.getContextURL().getServiceRoot();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/CountQueryMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/CountQueryMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import org.apache.olingo.server.api.ODataApplicationException;
import org.mockito.ArgumentMatcher;
import com.sap.olingo.jpa.processor.core.query.JPACountQuery;
public class CountQueryMatcher implements ArgumentMatcher<JPACountQuery> {
private final long extCountResult;
private boolean executed = false;
public CountQueryMatcher(long exp) {
extCountResult = exp;
}
@Override
public boolean matches(JPACountQuery query) {
if (query != null) {
if (extCountResult != 0 && !executed) {
try {
executed = true; // Query can be used only once but matcher is called twice
return extCountResult == query.countResults();
} catch (ODataApplicationException e) {
System.out.print(e.getMessage());
return false;
}
}
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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/PrimitiveSerializerOptionsMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/PrimitiveSerializerOptionsMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import java.net.URI;
import org.apache.olingo.server.api.serializer.PrimitiveSerializerOptions;
public class PrimitiveSerializerOptionsMatcher extends SerializerOptionsMatcher<PrimitiveSerializerOptions> {
public PrimitiveSerializerOptionsMatcher(final String pattern) {
super(pattern);
}
@Override
protected URI getService(final PrimitiveSerializerOptions options) {
return options.getContextURL().getServiceRoot();
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/util/matcher/SerializerOptionsMatcher.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/matcher/SerializerOptionsMatcher.java | package com.sap.olingo.jpa.processor.core.util.matcher;
import java.net.URI;
import org.mockito.ArgumentMatcher;
public abstract class SerializerOptionsMatcher<T> implements ArgumentMatcher<T> {
protected String extElement;
public SerializerOptionsMatcher(final String pattern) {
extElement = pattern;
}
@Override
public final boolean matches(final T options) {
return verify(getService(options));
}
protected abstract URI getService(T options);
private boolean verify(final URI serviceRoot) {
if (serviceRoot == null && extElement == null)
return true;
else if (serviceRoot != null && serviceRoot.toString().equals(extElement))
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/test/java/com/sap/olingo/jpa/processor/core/uri/JPASkipTokenOptionImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPASkipTokenOptionImplTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPASkipTokenOptionImplTest {
private JPASkipOptionImpl cut;
@BeforeEach
void setup() {
cut = new JPASkipOptionImpl(100);
}
@Test
void testGetName() {
assertNull(cut.getName());
}
@Test
void testGetText() {
assertEquals("100", cut.getText());
}
@Test
void testGetValue() {
assertEquals(100, cut.getValue());
}
@Test
void testGetKind() {
assertEquals(SystemQueryOptionKind.SKIP, cut.getKind());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/uri/JPAExpandItemTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPAExpandItemTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collection;
import org.apache.olingo.commons.api.edm.EdmType;
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.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
class JPAExpandItemTest {
private JPAExpandItem cut;
private LevelsExpandOption levels;
private ExpandItem item;
private EdmType typeFilter;
private ApplyOption apply;
private TopOption top;
private SkipOption skip;
private CountOption count;
@BeforeEach
void setup() {
levels = mock(LevelsExpandOption.class);
item = mock(ExpandItem.class);
typeFilter = mock(EdmType.class);
apply = mock(ApplyOption.class);
top = mock(TopOption.class);
skip = mock(SkipOption.class);
count = mock(CountOption.class);
when(item.hasCountPath()).thenReturn(true);
when(item.isRef()).thenReturn(true);
when(item.getStartTypeFilter()).thenReturn(typeFilter);
when(item.getApplyOption()).thenReturn(apply);
when(item.getTopOption()).thenReturn(top);
when(item.getSkipOption()).thenReturn(skip);
when(item.getCountOption()).thenReturn(count);
}
@TestFactory
Collection<DynamicTest> dynamicTestsNoItemProvided() {
cut = new JPAExpandItem(levels);
return Arrays.asList(
dynamicTest("isRef returns false", () -> assertFalse(cut.isRef())),
dynamicTest("hasCountPath returns false", () -> assertFalse(cut.hasCountPath())),
dynamicTest("getStartTypeFilter returns null", () -> assertNull(cut.getStartTypeFilter())),
dynamicTest("getApplyOption returns null", () -> assertNull(cut.getApplyOption())),
dynamicTest("getTopOption returns null", () -> assertNull(cut.getTopOption())),
dynamicTest("getSkipOption returns null", () -> assertNull(cut.getSkipOption())),
dynamicTest("getCountOption returns null", () -> assertNull(cut.getCountOption())));
}
@TestFactory
Collection<DynamicTest> dynamicTestsItemProvided() {
cut = new JPAExpandItem(item, levels);
return Arrays.asList(
dynamicTest("isRef returns original value", () -> assertTrue(cut.isRef())),
dynamicTest("hasCountPath returns original value", () -> assertTrue(cut.hasCountPath())),
dynamicTest("getStartTypeFilter returns original value", () -> assertEquals(typeFilter, cut
.getStartTypeFilter())),
dynamicTest("getApplyOption returns original value", () -> assertEquals(apply, cut.getApplyOption())),
dynamicTest("getTopOption returns original value", () -> assertEquals(top, cut.getTopOption())),
dynamicTest("getSkipOption returns original value", () -> assertEquals(skip, cut.getSkipOption())),
dynamicTest("getCountOption returns original value", () -> assertEquals(count, cut.getCountOption())));
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriParameterImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriParameterImplTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.UUID;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.core.edm.primitivetype.EdmGuid;
import org.apache.olingo.commons.core.edm.primitivetype.EdmString;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPAUriParameterImplTest {
private static final String ALIAS = "Alias";
private static final String NAME = "Name";
private JPAUriParameterImpl cut;
private EdmKeyPropertyRef propertyReference;
private EdmProperty property;
@BeforeEach
void setup() {
propertyReference = mock(EdmKeyPropertyRef.class);
property = mock(EdmProperty.class);
when(propertyReference.getAlias()).thenReturn(ALIAS);
when(propertyReference.getName()).thenReturn(NAME);
when(propertyReference.getProperty()).thenReturn(property);
when(property.getType()).thenReturn(EdmString.getInstance());
cut = new JPAUriParameterImpl(propertyReference, "Test");
}
@Test
void testGetReferencedPropertyIsNull() {
assertNull(cut.getReferencedProperty());
}
@Test
void testGetAlias() {
assertEquals(ALIAS, cut.getAlias());
}
@Test
void testGetName() {
assertEquals(NAME, cut.getName());
}
@Test
void testGetExpressionIsNull() {
assertNull(cut.getExpression());
}
@Test
void testGetTextString() {
assertEquals("'Test'", cut.getText());
}
@Test
void testGetTextUUID() {
final var id = UUID.randomUUID();
when(property.getType()).thenReturn(EdmGuid.getInstance());
cut = new JPAUriParameterImpl(propertyReference, id.toString());
assertEquals(id.toString(), cut.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/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriInfoResourceImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriInfoResourceImplTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import org.apache.olingo.server.api.uri.UriInfoResource;
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.FormatOption;
import org.apache.olingo.server.api.uri.queryoption.IdOption;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPAUriInfoResourceImplTest {
private JPAUriInfoResourceImpl cut;
private UriInfoResource original;
private CustomQueryOption customQueryOption;
private FormatOption formatOption;
private IdOption idOption;
private DeltaTokenOption deltaTokenOption;
@BeforeEach
void setup() {
original = mock(UriInfoResource.class);
customQueryOption = mock(CustomQueryOption.class);
formatOption = mock(FormatOption.class);
idOption = mock(IdOption.class);
deltaTokenOption = mock(DeltaTokenOption.class);
when(original.getCustomQueryOptions()).thenReturn(Collections.singletonList(customQueryOption));
when(original.getFormatOption()).thenReturn(formatOption);
when(original.getIdOption()).thenReturn(idOption);
when(original.getDeltaTokenOption()).thenReturn(deltaTokenOption);
when(original.getValueForAlias("@a")).thenReturn("Test");
cut = new JPAUriInfoResourceImpl(original);
}
@Test
void testGetCustomQueryOptions() {
assertEquals(customQueryOption, cut.getCustomQueryOptions().get(0));
}
@Test
void testGetValueForAlias() {
assertEquals("Test", cut.getValueForAlias("@a"));
}
@Test
void testGetFormatOption() {
assertEquals(formatOption, cut.getFormatOption());
}
@Test
void testGetIdOption() {
assertEquals(idOption, cut.getIdOption());
}
@Test
void testGetDeltaTokenOption() {
assertEquals(deltaTokenOption, cut.getDeltaTokenOption());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriInfoFactoryTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriInfoFactoryTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmSingleton;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoKind;
import org.apache.olingo.server.api.uri.UriInfoResource;
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.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourceSingleton;
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.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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAODataPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
class JPAUriInfoFactoryTest {
private JPAUriInfoFactory cut;
private UriInfo original;
private JPAODataPage page;
@BeforeEach
void setup() {
original = mock(UriInfo.class);
}
@Test
void testFactoryReturnsOriginalForDefaultPage() {
page = new JPAODataPage(original, 0, Integer.MAX_VALUE, "Test");
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNull(act.getTopOption());
assertNull(act.getSkipOption());
}
@Test
void testFactorySetSystemOptionForTop() {
page = new JPAODataPage(original, 0, 10, "Test");
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNotNull(act.getTopOption());
assertEquals(10, act.getTopOption().getValue());
assertNull(act.getSkipOption());
}
@Test
void testFactorySetSystemOptionForSkip() {
page = new JPAODataPage(original, 20, Integer.MAX_VALUE, "Test");
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNull(act.getTopOption());
assertNotNull(act.getSkipOption());
assertEquals(20, act.getSkipOption().getValue());
}
@Test
void testFactorySetSystemOptionForSkipToken() {
page = new JPAODataPage(original, 20, Integer.MAX_VALUE, "Test");
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNotNull(act.getSkipTokenOption());
assertEquals("Test", act.getSkipTokenOption().getValue());
}
@Test
void testFactoryRemoveSkipTokenIfNull() {
createSkipToken();
page = new JPAODataPage(original, 20, Integer.MAX_VALUE, null);
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNull(act.getSkipTokenOption());
}
@Test
void testFactoryReplaceSkipToken() {
createSkipToken();
page = new JPAODataPage(original, 20, Integer.MAX_VALUE, "New");
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNotNull(act.getSkipTokenOption());
assertEquals("New", act.getSkipTokenOption().getValue());
}
@Test
void testFactoryConvertsOneExpand() {
createUriInfoEntitySetOneExpand("Children");
page = new JPAODataPage(original, 20, 10, "New",
singletonList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertEquals(20, act.getSkipOption().getValue());
assertEquals(10, act.getTopOption().getValue());
assertEquals("New", act.getSkipTokenOption().getValue());
}
@Test
void testFactoryConvertsSingletonOneExpand() {
createUriInfoSingletonOneExpand("Children");
page = new JPAODataPage(original, 20, 10, "New",
singletonList(new JPAODataPageExpandInfo("Children", "")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertNotNull(act.getOrderByOption());
assertEquals(2, act.getUriResourceParts().size());
assertInstanceOf(UriResourceSingleton.class, act.getUriResourceParts().get(0));
assertFirstPagedNavigation(act);
}
@Test
void testFactoryConvertsTwoExpandsFirstPaged() {
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
final var expandSecondLevel = createExpandItem("Children");
final var expandOption = mock(ExpandOption.class);
when(expandOption.getExpandItems()).thenReturn(singletonList(expandSecondLevel));
when(expandOption.getKind()).thenReturn(SystemQueryOptionKind.EXPAND);
when(expandFirstLevel.getExpandOption()).thenReturn(expandOption);
page = new JPAODataPage(original, 20, 10, "New",
List.of(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertFirstPagedNavigation(act);
final var expand = act.getExpandOption();
assertNotNull(expand);
assertEquals(1, expand.getExpandItems().size());
}
@Test
void testFactoryConvertsTwoExpandsLastPaged() {
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
final var expandSecondLevel = createExpandItem("Children");
final var expandOption = mock(ExpandOption.class);
when(expandOption.getExpandItems()).thenReturn(singletonList(expandSecondLevel));
when(expandOption.getKind()).thenReturn(SystemQueryOptionKind.EXPAND);
when(expandFirstLevel.getExpandOption()).thenReturn(expandOption);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2"),
new JPAODataPageExpandInfo("Children", "Eurostat/NUTS2/BE22")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertSecondPagedResourceParts(act);
assertSecondPagedNavigation(act);
assertInstanceOf(UriResourceNavigation.class, act.getUriResourceParts().get(2));
assertEquals(20, act.getSkipOption().getValue());
assertEquals(10, act.getTopOption().getValue());
}
@Test
void testFactoryConvertsExpandLevels2FirstPaged() {
// ...Es?$expand=Navigation1($levels=2) => ...Es(key)/Navigation1?$expand=Navigation1
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
final var levelsOption = mock(LevelsExpandOption.class);
when(expandFirstLevel.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.getValue()).thenReturn(2);
page = new JPAODataPage(original, 20, 10, "New",
List.of(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertFirstPagedNavigation(act);
final var expand = act.getExpandOption();
assertNotNull(expand);
final var item = expand.getExpandItems().get(0);
final var part = (UriResourceNavigation) item.getResourcePath().getUriResourceParts().get(0);
assertEquals("Children", part.getProperty().getName());
assertEquals(1, item.getLevelsOption().getValue());
}
@Test
void testFactoryConvertsExpandLevels2SecondPaged() {
// ...Es?$expand=Navigation1($levels=2) => ...Es(key)/Navigation1?$expand=Navigation1
final var levelsOption = mock(LevelsExpandOption.class);
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
when(expandFirstLevel.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.getValue()).thenReturn(2);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2"),
new JPAODataPageExpandInfo("Children", "Eurostat/NUTS2/BE22")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertSecondPagedResourceParts(act);
assertSecondPagedNavigation(act);
final var expand = act.getExpandOption();
assertNull(expand);
}
@Test
void testFactoryConvertsExpandLevelsMaxFirstPaged() {
// ...Es?$expand=Navigation1($levels=max) => ...Es(key)/Navigation1?$expand=Navigation1($levels=max)
final var levelsOption = mock(LevelsExpandOption.class);
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
when(expandFirstLevel.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.getValue()).thenReturn(0);
when(levelsOption.isMax()).thenReturn(true);
page = new JPAODataPage(original, 20, 10, "New",
List.of(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertFirstPagedNavigation(act);
final var expand = act.getExpandOption();
assertNotNull(expand);
final var item = expand.getExpandItems().get(0);
final var part = (UriResourceNavigation) item.getResourcePath().getUriResourceParts().get(0);
assertEquals("Children", part.getProperty().getName());
assertTrue(item.getLevelsOption().isMax());
}
@Test
void testFactoryConvertsExpandFirstStar() {
// ...Es?$expand=* => ...Es(key)/Navigation1
final var expandItem = createUriInfoEntitySetOneExpand("Children");
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
page = new JPAODataPage(original, 20, 10, "New",
List.of(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertFirstPagedNavigation(act);
assertNull(act.getExpandOption());
}
@Test
void testFactoryConvertsExpandSecondStarFirstPaged() {
// ...Es?$expand=Navigation1($expand=*) => ...Es(key)/Navigation1?$expand=*
final var expandSecondLevel = createBaseUriInfoOneExpand("Children");
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandSecondLevel.getResourcePath()).thenReturn(resourceInfo);
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
createSecondStar(expandSecondLevel, expandFirstLevel);
page = new JPAODataPage(original, 20, 10, "New",
List.of(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertFirstPagedNavigation(act);
final var expand = act.getExpandOption();
assertNotNull(expand);
assertEquals(1, expand.getExpandItems().size());
assertTrue(expand.getExpandItems().get(0).isStar());
}
@Test
void testFactoryConvertsExpandSecondStarSecondPaged() {
// ...Es?$expand=Navigation1($expand=*) => ...Es(key)/Navigation1?($expand=Navigation1_2)
final var expandSecondLevel = createBaseUriInfoOneExpand("Children");
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandSecondLevel.getResourcePath()).thenReturn(resourceInfo);
final var expandFirstLevel = createUriInfoEntitySetOneExpand("Children");
createSecondStar(expandSecondLevel, expandFirstLevel);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2"),
new JPAODataPageExpandInfo("Children", "Eurostat/NUTS2/BE22")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertSecondPagedResourceParts(act);
assertSecondPagedNavigation(act);
final var expand = act.getExpandOption();
assertNull(expand);
}
@Test
void testFactoryConvertsExpandFirstStarLevels2FirstPaged() {
// ...Es?$expand=*($levels=2) => ...Es(key)/Navigation1?$expand=*
final var expandItem = createUriInfoEntitySetOneExpand("Children");
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
final var levelsOption = mock(LevelsExpandOption.class);
when(expandItem.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.getValue()).thenReturn(2);
page = new JPAODataPage(original, 20, 10, "New",
List.of(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertFirstPagedResourceParts(act);
assertFirstPagedNavigation(act);
final var expand = act.getExpandOption();
assertNotNull(expand);
assertEquals(1, expand.getExpandItems().size());
assertNotNull(expand.getExpandItems().get(0).getLevelsOption());
assertTrue(expand.getExpandItems().get(0).isStar());
assertEquals(1, expand.getExpandItems().get(0).getLevelsOption().getValue());
}
@Test
void testFactoryConvertsExpandFirstStarLevels2SecondPaged() {
// ...Es?$expand=*($levels=2) => ...Es(key)/Navigation1(key1)/Navigation1_1
final var expandItem = createUriInfoEntitySetOneExpand("Children");
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
final var levelsOption = mock(LevelsExpandOption.class);
when(expandItem.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.getValue()).thenReturn(2);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2"),
new JPAODataPageExpandInfo("Children", "Eurostat/NUTS2/BE22")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertEquals(3, act.getUriResourceParts().size());
final UriResourceEntitySet es = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = es.getKeyPredicates();
assertEquals(3, keys.size());
assertSecondPagedNavigation(act);
final var expand = act.getExpandOption();
assertNull(expand);
}
@Test
void testFactoryConvertsExpandFirstStarLevelsMaxSecondPaged() {
// ...Es?$expand=*($levels=max) => ...Es(key)/Navigation1(key1)/Navigation1_1?$expand=*($levels=max)
final var expandItem = createUriInfoEntitySetOneExpand("Children");
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
final var levelsOption = mock(LevelsExpandOption.class);
when(expandItem.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.isMax()).thenReturn(true);
when(levelsOption.getValue()).thenReturn(0);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2"),
new JPAODataPageExpandInfo("Children", "Eurostat/NUTS2/BE22")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertEquals(3, act.getUriResourceParts().size());
final UriResourceEntitySet es = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = es.getKeyPredicates();
assertEquals(3, keys.size());
assertSecondPagedNavigation(act);
final var expand = act.getExpandOption();
assertNotNull(expand);
assertEquals(1, expand.getExpandItems().size());
final var item = expand.getExpandItems().get(0);
assertTrue(item.isStar());
assertTrue(item.getLevelsOption().isMax());
}
@Test
void testFactoryConvertsExpandStarViaComplexType() {
// ...Es(key)/ComplexType?$expand=* => ...Es(key)/ComplexType/Navigation1
final var expandItem = createBaseUriInfoOneExpand("Children");
final var es = createEntitySet();
final EdmEntityType edmType = createEntityType();
final var complex = mock(UriResourceComplexProperty.class);
final var complexType = mock(EdmComplexType.class);
when(complex.getComplexType()).thenReturn(complexType);
when(complex.getType()).thenReturn(complexType);
when(complex.getKind()).thenReturn(UriResourceKind.complexProperty);
when(complex.getSegmentValue()).thenReturn("Complex");
when(complexType.getName()).thenReturn("Complex");
addNavigationPropertiesToType(complexType, edmType);
when(original.getUriResourceParts()).thenReturn(List.of(es, complex));
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Complex/Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertEquals(3, act.getUriResourceParts().size());
final UriResourceEntitySet actEs = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = actEs.getKeyPredicates();
assertEquals(3, keys.size());
assertTrue(act.getUriResourceParts().get(1) instanceof UriResourceComplexProperty);
assertTrue(act.getUriResourceParts().get(2) instanceof UriResourceNavigation);
}
@Test
void testFactoryConvertsExpandStarViaComplexWithIntermediateType() {
// ...Es(key)/ComplexType1?$expand=* => ...Es(key)/ComplexType1/ComplexType2/Navigation1
final var expandItem = createBaseUriInfoOneExpand("Children");
final var es = createEntitySet();
final EdmEntityType edmType = createEntityType();
final var complex = mock(UriResourceComplexProperty.class);
final var complexType = mock(EdmComplexType.class);
when(complex.getComplexType()).thenReturn(complexType);
when(complex.getType()).thenReturn(complexType);
when(complex.getSegmentValue()).thenReturn("Complex");
when(complex.getKind()).thenReturn(UriResourceKind.complexProperty);
when(complexType.getNavigationPropertyNames()).thenReturn(Collections.emptyList());
when(complexType.getPropertyNames()).thenReturn(List.of("Left", "Right"));
final var left = createNavigationViaComplexType(edmType, "Left");
when(complexType.getProperty("Left")).thenReturn(left);
final var right = createNavigationViaComplexType(edmType, "Right");
when(complexType.getProperty("Right")).thenReturn(right);
when(original.getUriResourceParts()).thenReturn(List.of(es, complex));
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Complex/Left/Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertEquals(4, act.getUriResourceParts().size());
final UriResourceEntitySet actEs = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = actEs.getKeyPredicates();
assertEquals(3, keys.size());
assertTrue(act.getUriResourceParts().get(1) instanceof UriResourceComplexProperty);
assertTrue(act.getUriResourceParts().get(2) instanceof UriResourceComplexProperty);
assertTrue(act.getUriResourceParts().get(3) instanceof UriResourceNavigation);
}
@Test
void testFactoryConvertsExpandStarViaToOneWithIntermediateType() {
// ...Es(key)/Navigation1?$expand=* => ...Es(key)/Navigation1/Navigation2
final var expandItem = createBaseUriInfoOneExpand("Children");
final var es = createEntitySet();
final EdmEntityType edmType = createEntityType();
final var navigation = createUriNavigationProperty("Parent", edmType);
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
when(expandItem.getResourcePath()).thenReturn(resourceInfo);
when(expandItem.isStar()).thenReturn(true);
final var levelsOption = mock(LevelsExpandOption.class);
when(expandItem.getLevelsOption()).thenReturn(levelsOption);
when(levelsOption.getValue()).thenReturn(2);
when(original.getUriResourceParts()).thenReturn(List.of(es, navigation));
page = new JPAODataPage(original, 20, 10, "New",
asList(new JPAODataPageExpandInfo("Children", "Eurostat/NUTS1/BE2")));
cut = new JPAUriInfoFactory(page);
final var act = cut.build();
assertEquals(3, act.getUriResourceParts().size());
final UriResourceEntitySet actEs = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = actEs.getKeyPredicates();
assertEquals(3, keys.size());
assertTrue(act.getUriResourceParts().get(1) instanceof UriResourceNavigation);
assertTrue(act.getUriResourceParts().get(2) instanceof UriResourceNavigation);
}
private EdmProperty createNavigationViaComplexType(final EdmEntityType edmType, final String name) {
final var property = mock(EdmProperty.class);
final var propertyType = mock(EdmStructuredType.class);
when(property.getType()).thenReturn(propertyType);
when(property.getName()).thenReturn(name);
addNavigationPropertiesToType(propertyType, edmType);
return property;
}
private static void createSecondStar(final ExpandItem expandSecondLevel, final ExpandItem expandFirstLevel) {
final var expandOption = mock(ExpandOption.class);
when(expandOption.getExpandItems()).thenReturn(singletonList(expandSecondLevel));
when(expandOption.getKind()).thenReturn(SystemQueryOptionKind.EXPAND);
when(expandFirstLevel.getExpandOption()).thenReturn(expandOption);
when(expandSecondLevel.isStar()).thenReturn(true);
}
private void assertFirstPagedNavigation(final JPAUriInfoResource act) {
assertInstanceOf(UriResourceNavigation.class, act.getUriResourceParts().get(1));
final UriResourceNavigation navigation = (UriResourceNavigation) act.getUriResourceParts().get(1);
assertEquals(20, act.getSkipOption().getValue());
assertEquals(10, act.getTopOption().getValue());
assertFalse(navigation.isCollection());
}
private void assertFirstPagedResourceParts(final JPAUriInfoResource act) {
assertNotNull(act.getOrderByOption());
assertEquals(2, act.getUriResourceParts().size());
final UriResourceEntitySet es = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = es.getKeyPredicates();
assertEquals(3, keys.size());
}
private SkipTokenOption createSkipToken() {
final SkipTokenOption skipToken = mock(SkipTokenOption.class);
when(original.getSkipTokenOption()).thenReturn(skipToken);
when(skipToken.getValue()).thenReturn("Old");
when(skipToken.getKind()).thenReturn(SystemQueryOptionKind.SKIPTOKEN);
when(original.getSystemQueryOptions()).thenReturn(singletonList(skipToken));
return skipToken;
}
private ExpandItem createUriInfoEntitySetOneExpand(final String name) {
final var item = createBaseUriInfoOneExpand(name);
final UriResourceEntitySet es = createEntitySet();
when(original.getUriResourceParts()).thenReturn(singletonList(es));
return item;
}
private UriResourceEntitySet createEntitySet() {
final UriResourceEntitySet es = mock(UriResourceEntitySet.class);
final EdmEntitySet edmEs = mock(EdmEntitySet.class);
final EdmEntityType edmType = createEntityType();
final var keyReferences = createKeyReferences();
when(es.getKind()).thenReturn(UriResourceKind.entitySet);
when(es.getEntitySet()).thenReturn(edmEs);
when(es.getEntityType()).thenReturn(edmType);
when(es.getType()).thenReturn(edmType);
when(edmType.getKeyPropertyRefs()).thenReturn(keyReferences);
return es;
}
private void createUriInfoSingletonOneExpand(final String name) {
createBaseUriInfoOneExpand(name);
final var singleton = mock(UriResourceSingleton.class);
final var edmSingleton = mock(EdmSingleton.class);
final var edmType = mock(EdmEntityType.class);
final var keyReferences = createKeyReferences();
when(original.getUriResourceParts()).thenReturn(singletonList(singleton));
when(singleton.getKind()).thenReturn(UriResourceKind.singleton);
when(singleton.getSingleton()).thenReturn(edmSingleton);
when(singleton.getEntityType()).thenReturn(edmType);
when(edmType.getKeyPropertyRefs()).thenReturn(keyReferences);
}
private ExpandItem createBaseUriInfoOneExpand(final String name) {
final var skipToken = createSkipToken();
final TopOption topOption = mock(TopOption.class);
final SkipOption skipOption = mock(SkipOption.class);
final FilterOption filterOption = mock(FilterOption.class);
final FormatOption formatOption = mock(FormatOption.class);
final ExpandOption expandOption = mock(ExpandOption.class);
final var item = createExpandItem(name);
when(topOption.getKind()).thenReturn(SystemQueryOptionKind.TOP);
when(skipOption.getKind()).thenReturn(SystemQueryOptionKind.SKIP);
when(filterOption.getKind()).thenReturn(SystemQueryOptionKind.FILTER);
when(formatOption.getKind()).thenReturn(SystemQueryOptionKind.FORMAT);
when(expandOption.getKind()).thenReturn(SystemQueryOptionKind.EXPAND);
when(original.getKind()).thenReturn(UriInfoKind.resource);
when(original.getSystemQueryOptions()).thenReturn(Arrays.asList(skipToken, topOption, skipOption, filterOption,
formatOption, expandOption));
when(original.getExpandOption()).thenReturn(expandOption);
when(original.getTopOption()).thenReturn(topOption);
when(original.getSkipOption()).thenReturn(skipOption);
when(original.getFilterOption()).thenReturn(filterOption);
when(original.getFormatOption()).thenReturn(formatOption);
when(expandOption.getExpandItems()).thenReturn(List.of(item));
return item;
}
private List<EdmKeyPropertyRef> createKeyReferences() {
final var codePublisher = mock(EdmKeyPropertyRef.class);
final var codeId = mock(EdmKeyPropertyRef.class);
final var divisionCode = mock(EdmKeyPropertyRef.class);
when(codePublisher.getName()).thenReturn("CodePublisher");
when(codeId.getName()).thenReturn("CodeId");
when(divisionCode.getName()).thenReturn("DivisionCode");
return Arrays.asList(codePublisher, codeId, divisionCode);
}
private ExpandItem createExpandItem(final String name) {
final ExpandItem item = mock(ExpandItem.class);
final UriInfoResource resourceInfo = mock(UriInfoResource.class);
final TopOption topOption = mock(TopOption.class);
final SkipOption skipOption = mock(SkipOption.class);
final FilterOption filterOption = mock(FilterOption.class);
final SelectOption selectOption = mock(SelectOption.class);
final SearchOption searchOption = mock(SearchOption.class);
final OrderByOption orderByOption = mock(OrderByOption.class);
when(topOption.getKind()).thenReturn(SystemQueryOptionKind.TOP);
when(skipOption.getKind()).thenReturn(SystemQueryOptionKind.SKIP);
when(filterOption.getKind()).thenReturn(SystemQueryOptionKind.FILTER);
when(selectOption.getKind()).thenReturn(SystemQueryOptionKind.SELECT);
when(searchOption.getKind()).thenReturn(SystemQueryOptionKind.SEARCH);
when(orderByOption.getKind()).thenReturn(SystemQueryOptionKind.ORDERBY);
when(item.getTopOption()).thenReturn(topOption);
when(item.getSkipOption()).thenReturn(skipOption);
when(item.getFilterOption()).thenReturn(filterOption);
when(item.getSelectOption()).thenReturn(selectOption);
when(item.getSearchOption()).thenReturn(searchOption);
when(item.getOrderByOption()).thenReturn(orderByOption);
when(item.getResourcePath()).thenReturn(resourceInfo);
final EdmEntityType edmType = createEntityType();
final UriResourceNavigation navigation = createUriNavigationProperty(name, edmType);
when(resourceInfo.getUriResourceParts()).thenReturn(List.of(navigation));
return item;
}
private EdmEntityType createEntityType() {
final EdmEntityType edmType = mock(EdmEntityType.class);
final var keyReferences = createKeyReferences();
when(edmType.getKeyPropertyRefs()).thenReturn(keyReferences);
addNavigationPropertiesToType(edmType, edmType);
when(edmType.getPropertyNames()).thenReturn(List.of());
return edmType;
}
private static UriResourceNavigation createUriNavigationProperty(final String name, final EdmEntityType edmType) {
final UriResourceNavigation navigation = mock(UriResourceNavigation.class);
final EdmNavigationProperty property = createNavigationProperty(name, edmType);
when(navigation.getSegmentValue()).thenReturn(name);
when(navigation.getProperty()).thenReturn(property);
when(navigation.getType()).thenReturn(edmType);
when(navigation.getKind()).thenReturn(UriResourceKind.navigationProperty);
return navigation;
}
private static EdmNavigationProperty createNavigationProperty(final String name, final EdmEntityType edmType) {
final EdmNavigationProperty property = mock(EdmNavigationProperty.class);
when(property.getName()).thenReturn(name);
when(property.getType()).thenReturn(edmType);
return property;
}
private void assertSecondPagedNavigation(final JPAUriInfoResource act) {
final var navigation = (UriResourceNavigation) act.getUriResourceParts().get(1);
final var navigationKeys = navigation.getKeyPredicates();
assertEquals(3, navigationKeys.size());
assertFalse(navigation.isCollection());
}
private void assertSecondPagedResourceParts(final JPAUriInfoResource act) {
assertNotNull(act.getOrderByOption());
assertEquals(3, act.getUriResourceParts().size());
final UriResourceEntitySet es = (UriResourceEntitySet) act.getUriResourceParts().get(0);
final var keys = es.getKeyPredicates();
assertEquals(3, keys.size());
}
private void addNavigationPropertiesToType(final EdmStructuredType source, final EdmEntityType target) {
when(source.getNavigationPropertyNames()).thenReturn(Arrays.asList("Children", "Parent"));
final EdmNavigationProperty children = createNavigationProperty("Children", target);
final EdmNavigationProperty parent = createNavigationProperty("Parent", target);
when(source.getNavigationProperty("Children")).thenReturn(children);
when(source.getNavigationProperty("Parent")).thenReturn(parent);
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/uri/JPASkipOptionImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPASkipOptionImplTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPASkipOptionImplTest {
private JPASkipTokenOptionImpl cut;
@BeforeEach
void setup() {
cut = new JPASkipTokenOptionImpl("Token");
}
@Test
void testGetName() {
assertNull(cut.getName());
}
@Test
void testGetText() {
assertEquals("Token", cut.getText());
}
@Test
void testGetValue() {
assertEquals("Token", cut.getValue());
}
@Test
void testGetKind() {
assertEquals(SystemQueryOptionKind.SKIPTOKEN, cut.getKind());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriResourceEntitySetImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPAUriResourceEntitySetImplTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.UUID;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
class JPAUriResourceEntitySetImplTest {
private static final String TO_STRING = "ToString";
private static final String SEGMENT_VALUE = "SegmentValue";
private JPAUriResourceEntitySetImpl cut;
private UriResourceEntitySet es;
private JPAODataPageExpandInfo expandInfo;
private EdmType type;
private EdmEntityType entityType;
private EdmEntitySet entitySet;
private EdmKeyPropertyRef keyReference;
private EdmType filterType;
@BeforeEach
void setup() {
type = mock(EdmType.class);
entityType = mock(EdmEntityType.class);
entitySet = mock(EdmEntitySet.class);
es = mock(UriResourceEntitySet.class);
keyReference = mock(EdmKeyPropertyRef.class);
expandInfo = new JPAODataPageExpandInfo("Test", UUID.randomUUID().toString());
when(es.getType()).thenReturn(type);
when(es.getEntityType()).thenReturn(entityType);
when(es.getEntitySet()).thenReturn(entitySet);
when(es.toString(true)).thenReturn(TO_STRING);
when(es.getSegmentValue(true)).thenReturn(SEGMENT_VALUE);
when(es.getSegmentValue()).thenReturn(SEGMENT_VALUE);
when(es.getKind()).thenReturn(UriResourceKind.entitySet);
when(es.getTypeFilterOnCollection()).thenReturn(filterType);
when(es.getTypeFilterOnEntry()).thenReturn(filterType);
when(entityType.getKeyPropertyRefs()).thenReturn(singletonList(keyReference));
cut = new JPAUriResourceEntitySetImpl(es, expandInfo);
}
@Test
void testGetType() {
assertEquals(type, cut.getType());
}
@Test
void testIsCollectionReturnsFalse() {
assertFalse(cut.isCollection());
}
@Test
void testToStringTrue() {
assertEquals(TO_STRING, cut.toString(true));
}
@Test
void testGetSegmentValueTrue() {
assertEquals(SEGMENT_VALUE, cut.getSegmentValue(true));
}
@Test
void testGetSegmentValue() {
assertEquals(SEGMENT_VALUE, cut.getSegmentValue());
}
@Test
void testGetKind() {
assertEquals(UriResourceKind.entitySet, cut.getKind());
}
@Test
void testGetEntityType() {
assertEquals(entityType, cut.getEntityType());
}
@Test
void testGetEntitySet() {
assertEquals(entitySet, cut.getEntitySet());
}
@Test
void testGetKeyPredicates() {
assertFalse(cut.getKeyPredicates().isEmpty());
}
@Test
void testGetTypeFilterOnCollection() {
assertEquals(filterType, cut.getTypeFilterOnCollection());
}
@Test
void testGetTypeFilterOnEntry() {
assertEquals(filterType, cut.getTypeFilterOnEntry());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/uri/JPATopOptionImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/uri/JPATopOptionImplTest.java | package com.sap.olingo.jpa.processor.core.uri;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPATopOptionImplTest {
private JPATopOptionImpl cut;
@BeforeEach
void setup() {
cut = new JPATopOptionImpl(100);
}
@Test
void testGetName() {
assertNull(cut.getName());
}
@Test
void testGetText() {
assertEquals("100", cut.getText());
}
@Test
void testGetValue() {
assertEquals(100, cut.getValue());
}
@Test
void testGetKind() {
assertEquals(SystemQueryOptionKind.TOP, cut.getKind());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/filter/JPAArithmeticOperatorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAArithmeticOperatorTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
class JPAArithmeticOperatorTest {
private CriteriaBuilder cb;
private JPAOperationConverter converter;
private Path<Integer> expression;
@SuppressWarnings("unchecked")
@BeforeEach
void setUp() {
converter = mock(JPAOperationConverter.class);
cb = mock(CriteriaBuilder.class);
expression = mock(Path.class);
}
@Test
void testMemberLiteralGetLeft_Member() throws ODataApplicationException {
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final JPALiteralOperator right = mock(JPALiteralOperator.class);
when(right.get()).thenReturn(5);
when(left.get()).thenAnswer(new Answer<Path<Integer>>() {
@Override
public Path<Integer> answer(final InvocationOnMock invocation) throws Throwable {
return expression;
}
});
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertEquals(expression, cut.getLeft(cb));
}
@Test
void testLiteralMemberGetLeft_Member() throws ODataApplicationException {
final JPAMemberOperator right = mock(JPAMemberOperator.class);
final JPALiteralOperator left = mock(JPALiteralOperator.class);
when(left.get()).thenReturn(5);
when(right.get()).thenAnswer(new Answer<Path<Integer>>() {
@Override
public Path<Integer> answer(final InvocationOnMock invocation) throws Throwable {
return expression;
}
});
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertEquals(expression, cut.getLeft(cb));
}
@SuppressWarnings("unchecked")
@Test
void testGetLeftLiteralLiteral_Left() throws ODataApplicationException {
final JPALiteralOperator right = mock(JPALiteralOperator.class);
final JPALiteralOperator left = mock(JPALiteralOperator.class);
final Integer leftValue = 5;
final Expression<Number> result = mock(Expression.class);
when(left.get()).thenReturn(leftValue);
when(right.get()).thenReturn(10);
when(cb.literal(leftValue)).thenAnswer(new Answer<Expression<Number>>() {
@Override
public Expression<Number> answer(final InvocationOnMock invocation) throws Throwable {
invocation.getArguments();
return result;
}
});
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
final Expression<Number> act = cut.getLeft(cb);
assertEquals(result, act);
}
@SuppressWarnings("unchecked")
@Test
void testGetLeftMemberMember_Left() throws ODataApplicationException {
final JPAMemberOperator right = mock(JPAMemberOperator.class);
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final Path<Integer> expressionRight = mock(Path.class);
when(right.get()).thenAnswer(new Answer<Path<Integer>>() {
@Override
public Path<Integer> answer(final InvocationOnMock invocation) throws Throwable {
return expressionRight;
}
});
when(left.get()).thenAnswer(new Answer<Path<Integer>>() {
@Override
public Path<Integer> answer(final InvocationOnMock invocation) throws Throwable {
return expression;
}
});
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertEquals(expression, cut.getLeft(cb));
}
@Test
void testMemberLiteralGetRightAsNumber_Right() throws ODataApplicationException {
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final JPALiteralOperator right = mock(JPALiteralOperator.class);
final JPAAttribute attribute = mock(JPAAttribute.class);
when(right.get(attribute)).thenReturn(new BigDecimal("5.1"));
when(left.determineAttribute()).thenReturn(attribute);
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertEquals(new BigDecimal("5.1"), cut.getRightAsNumber(cb));
}
@Test
void testLiteralMemberGetRightAsNumber_Left() throws ODataApplicationException {
final JPAMemberOperator right = mock(JPAMemberOperator.class);
final JPALiteralOperator left = mock(JPALiteralOperator.class);
final JPAAttribute attribute = mock(JPAAttribute.class);
when(left.get(attribute)).thenReturn(new BigDecimal("5.1"));
when(right.determineAttribute()).thenReturn(attribute);
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertEquals(new BigDecimal("5.1"), cut.getRightAsNumber(cb));
}
@Test
void testLiteralLiteralGetRightAsNumber_Right() throws ODataApplicationException {
final JPALiteralOperator right = mock(JPALiteralOperator.class);
final JPALiteralOperator left = mock(JPALiteralOperator.class);
when(left.get()).thenReturn(new BigDecimal("5.1"));
when(right.get()).thenReturn(new BigDecimal("10.1"));
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertEquals(new BigDecimal("10.1"), cut.getRightAsNumber(cb));
}
@Test
void testGetMemberMemberGetRightAsNumber_Exception() {
final JPAMemberOperator right = mock(JPAMemberOperator.class);
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final JPAAttribute attribute = mock(JPAAttribute.class);
when(left.determineAttribute()).thenReturn(attribute);
when(right.determineAttribute()).thenReturn(attribute);
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertThrows(ODataApplicationException.class, () -> cut.getRightAsNumber(cb));
}
@Test
void testGetBooleanMemberGetRightAsNumber_Exception() {
final JPAMemberOperator right = mock(JPAMemberOperator.class);
final JPABooleanOperatorImp left = mock(JPABooleanOperatorImp.class);
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertThrows(ODataApplicationException.class, () -> cut.getRightAsNumber(cb));
}
@Test
void testGetMemberBooleanGetRightAsNumber_Exception() {
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final JPABooleanOperatorImp right = mock(JPABooleanOperatorImp.class);
final JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right);
assertThrows(ODataApplicationException.class, () -> cut.getRightAsNumber(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/test/java/com/sap/olingo/jpa/processor/core/filter/JPAInOperatorImplTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAInOperatorImplTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import org.apache.olingo.server.api.ODataApplicationException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class JPAInOperatorImplTest {
private JPAOperationConverter converter;
private JPAInOperatorImpl<String, JPALiteralOperator> cut;
@BeforeEach
void setUp() {
converter = mock(JPAOperationConverter.class);
}
@SuppressWarnings("unchecked")
@Test
void testGetCallsConverter() throws ODataApplicationException {
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final List<JPALiteralOperator> right = new ArrayList<>();
final Expression<Boolean> exp = mock(Expression.class);
when(converter.convert(any(JPAInOperator.class))).thenReturn(exp);
cut = new JPAInOperatorImpl<>(converter, left, right);
assertEquals(exp, cut.get());
verify(converter).convert(cut);
}
@Test
void testGetName() {
cut = new JPAInOperatorImpl<>(converter, null, null);
assertEquals("IN", cut.getName());
}
@SuppressWarnings("unchecked")
@Test
void testGetLeft() throws ODataApplicationException {
final JPAMemberOperator left = mock(JPAMemberOperator.class);
final Path<String> exp = mock(Path.class);
doReturn(exp).when(left).get();
cut = new JPAInOperatorImpl<>(converter, left, null);
assertEquals(exp, cut.getLeft());
}
@Test
void testGetFixValues() {
final List<JPALiteralOperator> right = new ArrayList<>();
cut = new JPAInOperatorImpl<>(converter, null, right);
assertEquals(right, cut.getFixValues());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/filter/JPAJavaFunctionOperatorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAJavaFunctionOperatorTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmParameter;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAODataQueryContext;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctionType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
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.testobjects.TestFunctionForFilter;
class JPAJavaFunctionOperatorTest {
private static final String EXTERNAL_NAME = "At";
private JPAJavaFunctionOperator cut;
private JPAVisitor jpaVisitor;
private JPAJavaFunction jpaFunction;
private UriResourceFunction resource;
private JPAServiceDocument sd;
private CriteriaBuilder cb;
private From<?, ?> from;
private List<UriParameter> uriParameters;
@BeforeEach
void setUp() {
jpaVisitor = mock(JPAVisitor.class);
jpaFunction = mock(JPAJavaFunction.class);
resource = mock(UriResourceFunction.class);
sd = mock(JPAServiceDocument.class);
cb = mock(CriteriaBuilder.class);
from = mock(From.class);
uriParameters = new ArrayList<>();
when(jpaVisitor.getSd()).thenReturn(sd);
when(jpaFunction.getFunctionType()).thenReturn(EdmFunctionType.JavaClass);
when(jpaFunction.getExternalName()).thenReturn(EXTERNAL_NAME);
when(jpaVisitor.getCriteriaBuilder()).thenReturn(cb);
doReturn(from).when(jpaVisitor).getRoot();
when(resource.getParameters()).thenReturn(uriParameters);
cut = new JPAJavaFunctionOperator(jpaVisitor, resource, jpaFunction);
}
@Test
void testGetNameReturnsExternalName() {
assertEquals(EXTERNAL_NAME, cut.getName());
}
@Test
void testGetExecutesFunction() throws NoSuchMethodException, SecurityException, ODataApplicationException,
ODataJPAModelException, EdmPrimitiveTypeException {
final LocalDate parameterValue = LocalDate.now();
final UriParameter uriParameter = mock(UriParameter.class);
final JPAParameter jpaParameter = mock(JPAParameter.class);
final EdmParameter edmParameter = mock(EdmParameter.class);
final EdmPrimitiveType edmType = mock(EdmPrimitiveType.class);
final EdmFunction edmFunction = mock(EdmFunction.class);
final Method m = TestFunctionForFilter.class.getMethod("at", LocalDate.class);
doReturn(TestFunctionForFilter.class.getConstructor(JPAODataQueryContext.class)).when(jpaFunction).getConstructor();
doReturn(m).when(jpaFunction).getMethod();
when(uriParameter.getName()).thenReturn("date");
when(uriParameter.getText()).thenReturn(parameterValue.toString());
uriParameters.add(uriParameter);
when(jpaFunction.getParameter(m.getParameters()[0])).thenReturn(jpaParameter);
when(jpaParameter.getName()).thenReturn("date");
when(resource.getFunction()).thenReturn(edmFunction);
when(edmFunction.getParameter("date")).thenReturn(edmParameter);
when(edmParameter.getType()).thenReturn(edmType);
when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE);
when(edmType.valueOfString(any(), any(), any(), any(), any(), any(), any())).thenReturn(parameterValue);
cut.get();
verify(cb).lessThanOrEqualTo(any(), eq(parameterValue));
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/filter/JPADBFunctionOperatorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPADBFunctionOperatorTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
class JPADBFunctionOperatorTest {
private CriteriaBuilder cb;
private JPADBFunctionOperator cut;
private UriResourceFunction uriFunction;
private JPAVisitor jpaVisitor;
private JPADataBaseFunction jpaFunction;
private JPAOperationResultParameter jpaResultParam;
private List<UriParameter> uriParams;
@BeforeEach
void setUp() {
cb = mock(CriteriaBuilder.class);
jpaVisitor = mock(JPAVisitor.class);
when(jpaVisitor.getCriteriaBuilder()).thenReturn(cb);
uriFunction = mock(UriResourceFunction.class);
jpaFunction = mock(JPADataBaseFunction.class);
jpaResultParam = mock(JPAOperationResultParameter.class);
when(jpaFunction.getResultParameter()).thenReturn(jpaResultParam);
final List<UriResource> resources = new ArrayList<>();
resources.add(uriFunction);
uriParams = new ArrayList<>();
cut = new JPADBFunctionOperator(jpaVisitor, uriParams, jpaFunction);
}
@SuppressWarnings("unchecked")
@Test
void testReturnsExpression() throws ODataApplicationException {
final Expression<?>[] jpaParameter = new Expression<?>[0];
when(jpaFunction.getDBName()).thenReturn("Test");
doReturn(Integer.valueOf(5).getClass()).when(jpaResultParam).getType();
when(cb.function(jpaFunction.getDBName(), jpaResultParam.getType(), jpaParameter)).thenReturn(mock(
Expression.class));
when(jpaFunction.getResultParameter()).thenReturn(jpaResultParam);
final Expression<?> act = cut.get();
assertNotNull(act);
}
@Test
void testAbortOnNonFunctionReturnsCollection() {
when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings");
when(jpaResultParam.isCollection()).thenReturn(true);
assertThrows(ODataApplicationException.class, () -> cut.get(), "Function provided not checked");
}
@Test
void testAbortOnNonScalarFunction() {
when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings");
when(jpaResultParam.isCollection()).thenReturn(false);
doReturn(AdministrativeDivision.class).when(jpaResultParam).getType();
assertThrows(ODataApplicationException.class, () -> cut.get());
}
@Test
void testAbortOnParameterReadException() throws ODataJPAModelException {
when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings");
doReturn(Integer.valueOf(5).getClass()).when(jpaResultParam).getType();
when(jpaFunction.getParameter()).thenThrow(ODataJPAModelException.class);
final ODataJPAProcessorException act = assertThrows(ODataJPAProcessorException.class, () -> cut.get());
assertEquals(500, act.getStatusCode());
}
@Test
void testReturnsName() {
when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings");
assertEquals("org.apache.olingo.jpa::Siblings", cut.getName());
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/filter/JPAVisitorTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAVisitorTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.ex.ODataException;
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.UriResourceFunction;
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.Member;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction;
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.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery;
class JPAVisitorTest {
private JPAEntityType et;
private From<?, ?> from;
private JPAFilterComplierAccess compiler;
private JPAAbstractQuery query;
private JPAExpressionVisitor cut;
private JPAODataDatabaseOperations extension;
private JPAOperationConverter converter;
@BeforeEach
public void setUp() throws ODataException {
final JPAODataQueryDirectives directives = JPAODataServiceContext.with()
.useQueryDirectives()
.build()
.build()
.getQueryDirectives();
extension = mock(JPAODataDatabaseOperations.class);
converter = new JPAOperationConverter(mock(CriteriaBuilder.class), extension, directives);
compiler = mock(JPAFilterComplierAccess.class);
query = mock(JPAAbstractQuery.class);
from = mock(From.class);
et = mock(JPAEntityType.class);
doReturn(from).when(compiler).getRoot();
when(compiler.getJpaEntityType()).thenReturn(et);
when(compiler.getConverter()).thenReturn(converter);
when(compiler.getParent()).thenReturn(query);
when(compiler.getDebugger()).thenReturn(mock(JPAServiceDebugger.class));
when(query.getDebugger()).thenReturn(mock(JPAServiceDebugger.class));
cut = new JPAVisitor(compiler);
}
@Test
void testGetEntityType() {
assertEquals(et, cut.getEntityType());
}
@Test
void testGetRoot() {
assertEquals(from, cut.getRoot());
}
@Test
void testVisitAliasThrowsException() {
assertThrows(ODataJPAFilterException.class, () -> cut.visitAlias("Test"));
}
@Test
void testVisitLambdaExpressionThrowsException() {
assertThrows(ODataJPAFilterException.class, () -> cut.visitLambdaExpression(null, null, null));
}
@Test
void testVisitLambdaReferenceThrowsException() {
assertThrows(ODataJPAFilterException.class, () -> cut.visitLambdaReference("Test"));
}
@Test
void testVisitTypeLiteralThrowsException() {
assertThrows(ODataJPAFilterException.class, () -> cut.visitTypeLiteral(null));
}
@Test
void createFunctionOperation() throws ExpressionVisitException, ODataApplicationException {
// final UriResource resource = member.getResourcePath().getUriResourceParts().get(0);
final Member member = mock(Member.class);
final UriInfoResource info = mock(UriInfoResource.class);
final UriResourceFunction uriFunction = mock(UriResourceFunction.class);
final List<UriResource> resources = new ArrayList<>();
resources.add(uriFunction);
when(member.getResourcePath()).thenReturn(info);
when(info.getUriResourceParts()).thenReturn(resources);
// final JPAFunction jpaFunction = this.jpaComplier.getSd().getFunction(((UriResourceFunction) resource).getFunction());
final JPAServiceDocument sd = mock(JPAServiceDocument.class);
final JPADataBaseFunction jpaFunction = mock(JPADataBaseFunction.class);
final EdmFunction edmFunction = mock(EdmFunction.class);
when(uriFunction.getFunction()).thenReturn(edmFunction);
when(compiler.getSd()).thenReturn(sd);
when(sd.getFunction(edmFunction)).thenReturn(jpaFunction);
when(uriFunction.getParameters()).thenReturn(new ArrayList<>());
assertTrue(cut.visitMember(member) instanceof JPADBFunctionOperator);
}
@Test
void testVisitBinaryOperatorWithListThrowsExceptionNotIn() {
final List<JPAOperator> right = new ArrayList<>();
assertThrows(ODataJPAFilterException.class, () -> cut.visitBinaryOperator(BinaryOperatorKind.HAS, null, right));
}
@Test
void testVisitBinaryOperatorWithListAllowsIn() throws ExpressionVisitException, ODataApplicationException {
final JPAOperator left = mock(JPAOperator.class);
final List<JPAOperator> right = new ArrayList<>();
assertNotNull(cut.visitBinaryOperator(BinaryOperatorKind.IN, left, right));
}
}
| 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/test/java/com/sap/olingo/jpa/processor/core/filter/JPAOperationConverterTest.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/JPAOperationConverterTest.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaBuilder.In;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
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.queryoption.expression.BinaryOperatorKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
class JPAOperationConverterTest {
private CriteriaBuilder cb;
private Expression<Number> expressionLeft;
private Expression<Number> expressionRight;
private JPAOperationConverter cut;
private JPAODataDatabaseOperations extension;
private JPAODataQueryDirectives directives;
@SuppressWarnings("unchecked")
@BeforeEach
void setUp() throws Exception {
directives = JPAODataServiceContext.with()
.useQueryDirectives()
.build()
.build()
.getQueryDirectives();
cb = mock(CriteriaBuilder.class);
extension = mock(JPAODataDatabaseOperations.class);
cut = new JPAOperationConverter(cb, extension, directives);
expressionLeft = mock(Path.class);
expressionRight = mock(Path.class);
}
@Test
void testAddMemberMember() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.ADD);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsExpression()).thenReturn(expressionRight);
when(cb.sum(expressionLeft, expressionRight)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testAddMemberLiteral() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.ADD);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsNumber(cb)).thenReturn(5);
when(cb.sum(expressionLeft, 5)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testSubMemberMember() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.SUB);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsExpression()).thenReturn(expressionRight);
when(cb.diff(expressionLeft, expressionRight)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testSubMemberLiteral() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.SUB);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsNumber(cb)).thenReturn(5);
when(cb.diff(expressionLeft, 5)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testDivMemberMember() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.DIV);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsExpression()).thenReturn(expressionRight);
when(cb.quot(expressionLeft, expressionRight)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testDivMemberLiteral() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.DIV);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsNumber(cb)).thenReturn(5);
when(cb.quot(expressionLeft, 5)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testMulMemberMember() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.MUL);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsExpression()).thenReturn(expressionRight);
when(cb.prod(expressionLeft, expressionRight)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testMulMemberLiteral() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
@SuppressWarnings("unchecked")
final Expression<Number> result = mock(Path.class);
when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class));
when(operator.getOperator()).thenReturn(BinaryOperatorKind.MUL);
when(operator.getLeft(cb)).thenReturn(expressionLeft);
when(operator.getRightAsNumber(cb)).thenReturn(5);
when(cb.prod(expressionLeft, 5)).thenReturn(result);
final Expression<?> act = cut.convert(operator);
assertEquals(result, act);
}
@Test
void testUnknownOperation_CallExtension() throws ODataApplicationException {
final JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class);
when(operator.getOperator()).thenReturn(BinaryOperatorKind.AND);
when(extension.convert(operator)).thenThrow(new ODataApplicationException(null, HttpStatusCode.NOT_IMPLEMENTED
.getStatusCode(), null));
final ODataApplicationException act = assertThrows(ODataApplicationException.class, () -> cut.convert(operator));
assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), act.getStatusCode());
}
@SuppressWarnings("unchecked")
@Test
void testConvertInOperatorNotInThrowsException() {
final JPAInOperator<String, JPAOperator> jpaOperator = mock(JPAInOperator.class);
when(jpaOperator.getOperator()).thenReturn(BinaryOperatorKind.HAS);
final var act = assertThrows(ODataJPAFilterException.class, () -> cut.convert(jpaOperator));
assertEquals(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR.getKey(), act.getId());
}
@SuppressWarnings("unchecked")
@Test
void testConvertInOperatorInNotSupportedThrowsException() {
final JPAInOperator<String, JPAOperator> jpaOperator = mock(JPAInOperator.class);
when(jpaOperator.getOperator()).thenReturn(BinaryOperatorKind.IN);
final var act = assertThrows(ODataJPAFilterException.class, () -> cut.convert(jpaOperator));
assertEquals(ODataJPAFilterException.MessageKeys.NOT_SUPPORTED_OPERATOR.getKey(), act.getId());
}
@SuppressWarnings("unchecked")
@Test
void testConvertInOperatorTooManyValuesThrowsException() throws ODataException {
directives = JPAODataServiceContext.with()
.useQueryDirectives()
.maxValuesInInClause(10)
.build()
.build()
.getQueryDirectives();
cut = new JPAOperationConverter(cb, extension, directives);
final List<JPAOperator> values = buildValuesList(20);
final In<Object> inOperation = mock(In.class);
final JPAInOperator<String, JPAOperator> jpaOperator = mock(JPAInOperator.class);
when(jpaOperator.getOperator()).thenReturn(BinaryOperatorKind.IN);
when(cb.in(any())).thenReturn(inOperation);
when(jpaOperator.getFixValues()).thenReturn(values);
final var act = assertThrows(ODataJPAFilterException.class, () -> cut.convert(jpaOperator));
assertEquals(ODataJPAFilterException.MessageKeys.NO_VALUES_OUT_OF_LIMIT.getKey(), act.getId());
}
private List<JPAOperator> buildValuesList(final int i) {
final List<JPAOperator> result = new ArrayList<>(i);
for (int count = 0; count < i; count++) {
result.add(mock(JPAOperator.class));
}
return result;
}
} | 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/test/java/com/sap/olingo/jpa/processor/core/filter/TestJavaFunctions.java | jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJavaFunctions.java | package com.sap.olingo.jpa.processor.core.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper;
class TestJavaFunctions {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static EntityManagerFactory emf;
protected Map<String, List<String>> headers;
protected static JPADefaultEdmNameBuilder nameBuilder;
protected static DataSource ds;
@BeforeAll
public static void setupClass() {
ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
emf.getProperties();
}
@Test
void testFilterOnFunction() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds,
"TemporalWithValidityPeriods?$filter=com.sap.olingo.jpa.At(Date=2022-12-01)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ArrayNode jobs = helper.getValues();
assertEquals(2, jobs.size());
}
@Test
void testFilterOnFunctionViaNavigation() throws IOException, ODataException {
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds,
"Persons('99')/Jobs?$filter=com.sap.olingo.jpa.At(Date=2022-12-01)",
"com.sap.olingo.jpa.processor.core.testobjects");
helper.assertStatus(200);
final ArrayNode jobs = helper.getValues();
assertEquals(1, jobs.size());
assertEquals("2022-11-01", jobs.get(0).get("ValidityStartDate").asText());
}
}
| 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.