repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/SelectOptionUtil.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/SelectOptionUtil.java | package com.sap.olingo.jpa.processor.core.query;
import java.util.stream.Collectors;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.uri.queryoption.SelectItem;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.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.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys;
/**
*
*
* @author Oliver Grande
* Created: 01.11.2019
*
*/
class SelectOptionUtil {
private SelectOptionUtil() {
super();
}
public static JPAPath selectItemAsPath(final JPAStructuredType jpaEntity, final String pathPrefix,
final SelectItem sItem) throws ODataJPAQueryException {
try {
final String pathItem = sItem.getResourcePath().getUriResourceParts().stream().map(path -> (path
.getSegmentValue())).collect(Collectors.joining(JPAPath.PATH_SEPARATOR));
final JPAPath selectItemPath = jpaEntity.getPath(pathPrefix.isEmpty() ? pathItem : pathPrefix
+ JPAPath.PATH_SEPARATOR + pathItem);
if (selectItemPath == null)
throw new ODataJPAQueryException(MessageKeys.QUERY_PREPARATION_INVALID_SELECTION_PATH,
HttpStatusCode.BAD_REQUEST);
return selectItemPath;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
public static boolean selectAll(final SelectOption select) {
return select == null || select.getSelectItems() == null || select.getSelectItems().isEmpty() || select
.getSelectItems().get(0).isStar();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/ExpressionUtility.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/query/ExpressionUtility.java | package com.sap.olingo.jpa.processor.core.query;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ATTRIBUTE_NOT_FOUND;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameterFacet;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.cb.ProcessorCriteriaBuilder;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.filter.JPAInvertibleVisitableExpression;
public final class ExpressionUtility {
public static final int CONTAINS_ONLY_LANGU = 1;
public static final int CONTAINS_LANGU_COUNTRY = 2;
public static final String SELECT_ITEM_SEPARATOR = ",";
private ExpressionUtility() {}
public static Expression<Boolean> createEQExpression(final OData odata, final CriteriaBuilder cb,
final From<?, ?> root, final JPAEntityType jpaEntity, final UriParameter keyPredicate)
throws ODataJPAFilterException, ODataJPAModelException {
try {
final JPAPath path = getJPAPath(jpaEntity, keyPredicate.getName());
final JPAAttribute attribute = path.getLeaf();
return cb.equal(convertToCriteriaPath(root, path.getPath()), convertValueOnAttribute(odata, attribute,
keyPredicate.getText()));
} catch (final ODataJPAProcessorException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* Converts the jpaPath into a Criteria Path.
* @param joinTables
* @param root
* @param jpaPath
* @return
*/
@SuppressWarnings("unchecked")
public static <T> Path<T> convertToCriteriaPath(final Map<String, From<?, ?>> joinTables, final From<?, ?> root,
final JPAPath jpaPath) {
Path<?> path = root;
for (final JPAElement jpaPathElement : jpaPath.getPath())
if (jpaPathElement instanceof final JPADescriptionAttribute descriptionAttribute) {
final Join<?, ?> join = (Join<?, ?>) joinTables.get(jpaPath.getAlias());
path = join.get(descriptionAttribute.getDescriptionAttribute().getInternalName());
} else if (jpaPathElement instanceof JPACollectionAttribute) {
path = joinTables.get(jpaPathElement.getExternalName());
} else {
path = path.get(jpaPathElement.getInternalName());
}
return (Path<T>) path;
}
@SuppressWarnings("unchecked")
public static <T> Path<T> convertToCriteriaPath(final From<?, ?> root, final List<JPAElement> jpaPath) {
Path<?> path = root;
for (final JPAElement jpaPathElement : jpaPath)
path = path.get(jpaPathElement.getInternalName());
return (Path<T>) path;
}
public static List<Path<Comparable<?>>> convertToCriteriaPaths(final From<?, ?> from, final List<JPAPath> jpaPaths) {
return jpaPaths.stream()
.map(jpaPath -> ExpressionUtility.<Comparable<?>> convertToCriteriaPath(from, jpaPath.getPath()))
.toList();
}
public static Object convertValueOnAttribute(final OData odata, final JPAAttribute attribute, final String value)
throws ODataJPAFilterException {
return convertValueOnAttribute(odata, attribute, value, true);
}
@SuppressWarnings("unchecked")
public static <T> Object convertValueOnAttribute(final OData odata, final JPAAttribute attribute, final String value,
final Boolean isUri) throws ODataJPAFilterException {
try {
final CsdlProperty edmProperty = (CsdlProperty) attribute.getProperty();
// TODO literal does not convert decimals without scale properly
String targetValue = null;
final EdmPrimitiveType edmType = odata.createPrimitiveTypeInstance(attribute.getEdmType());
if (Boolean.TRUE.equals(isUri)) {
targetValue = edmType.fromUriLiteral(value);
} else {
targetValue = value;
}
// Converter
if (attribute.getConverter() != null) {
final AttributeConverter<?, T> dbConverter = attribute.getConverter();
return dbConverter.convertToEntityAttribute(
(T) edmType.valueOfString(targetValue, edmProperty.isNullable(), edmProperty.getMaxLength(),
edmProperty.getPrecision(), edmProperty.getScale(), true, attribute.getType()));
} else {
return edmType.valueOfString(targetValue, edmProperty.isNullable(), edmProperty.getMaxLength(),
edmProperty.getPrecision(), edmProperty.getScale(), true, attribute.getType());
}
} catch (EdmPrimitiveTypeException | ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
public static Object convertValueOnFacet(final OData odata, final JPAParameterFacet returnType, final String value)
throws ODataJPAFilterException {
try {
final EdmPrimitiveTypeKind edmTypeKind = EdmPrimitiveTypeKind.valueOfFQN(returnType.getTypeFQN());
final EdmPrimitiveType edmType = odata.createPrimitiveTypeInstance(edmTypeKind);
String targetValue;
targetValue = edmType.fromUriLiteral(value);
return edmType.valueOfString(targetValue, true, returnType.getMaxLength(), returnType.getPrecision(), returnType
.getScale(), true, returnType.getType());
} catch (EdmPrimitiveTypeException | ODataJPAModelException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
public static Locale determineFallbackLocale(final Map<String, List<String>> headers) {
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html (14.4 accept language header
// example: Accept-Language : da, en-gb;q=0.8, en;q=0.7)
final List<String> languageHeaders = headers.get("accept-language");
if (languageHeaders != null) {
final String languageHeader = languageHeaders.get(0);
if (languageHeader != null) {
final String[] localeList = languageHeader.split(SELECT_ITEM_SEPARATOR);
final String locale = localeList[0];
final String[] languCountry = locale.split("-");
if (languCountry.length == CONTAINS_LANGU_COUNTRY)
return new Locale(languCountry[0], languCountry[1]);
else if (languCountry.length == CONTAINS_ONLY_LANGU)
return new Locale(languCountry[0]);
else
return Locale.ENGLISH;
}
}
return Locale.ENGLISH;
}
public static Expression<Boolean> createSubQueryBasedExpression(final Subquery<List<Comparable<?>>> query,
final List<Path<Comparable<?>>> jpaPath, final CriteriaBuilder cb, final VisitableExpression expression) {
final Expression<Boolean> subQueryExpression;
if (!jpaPath.isEmpty()) {
if (jpaPath.size() == 1)
subQueryExpression = cb.<Object> in(jpaPath.get(0)).value(query);
else
subQueryExpression = ((ProcessorCriteriaBuilder) cb).in(jpaPath, query);
} else {
subQueryExpression = cb.exists(query);
}
if (expression instanceof final JPAInvertibleVisitableExpression visitableExpression
&& visitableExpression.isInversionRequired()) {
visitableExpression.inversionPerformed();
return cb.not(subQueryExpression);
}
return subQueryExpression;
}
@Nonnull
private static JPAPath getJPAPath(final JPAStructuredType st, final String name) throws ODataJPAModelException,
ODataJPAProcessorException {
final var jpaPath = st.getPath(name);
if (jpaPath != null)
return jpaPath;
else
throw new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND, HttpStatusCode.INTERNAL_SERVER_ERROR, name);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAETagValidationResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAETagValidationResult.java | package com.sap.olingo.jpa.processor.core.processor;
import org.apache.olingo.commons.api.http.HttpStatusCode;
enum JPAETagValidationResult {
NOT_MODIFIED(HttpStatusCode.NOT_MODIFIED),
SUCCESS(HttpStatusCode.OK),
PRECONDITION_FAILED(HttpStatusCode.PRECONDITION_FAILED);
private final HttpStatusCode statusCode;
JPAETagValidationResult(final HttpStatusCode statusCode) {
this.statusCode = statusCode;
}
HttpStatusCode getStatusCode() {
return statusCode;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAActionRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAActionRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ACTION_UNKNOWN;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.deserializer.ODataDeserializer;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceAction;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAction;
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.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
public class JPAActionRequestProcessor extends JPAOperationRequestProcessor {
public JPAActionRequestProcessor(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
}
/**
* Execution of an action. Action selection for overloaded actions, as described in
* <a href="https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part1-protocol.html#_Toc31359015">
* Action Overload Resolution (part1 protocol 11.5.5.2)</a> is done by Olingo. Example:
* <p>
* In case an action is defined with binding parameter Business Partner, the action is also available at
* Organizations. In this case Olingo provides the action with binding parameter Business Partner.
*
*
* @param request
* @param response
* @param requestFormat
* @throws ODataApplicationException
*/
public void performAction(final ODataRequest request, final ODataResponse response, final ContentType requestFormat)
throws ODataApplicationException {
final List<UriResource> resourceList = uriInfo.getUriResourceParts();
final UriResourceAction resource = (UriResourceAction) resourceList.get(resourceList.size() - 1);
try {
final JPAAction jpaAction = sd.getAction(resource.getAction());
if (jpaAction == null)
throw new ODataJPAProcessorException(ACTION_UNKNOWN, BAD_REQUEST, resource.getAction().getName());
final Object instance = createInstance(jpaAction, em, requestContext.getHeader(), requestContext
.getRequestParameter());
final ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
final Map<String, org.apache.olingo.commons.api.data.Parameter> actionParameter =
deserializer.actionParameters(request.getBody(), resource.getAction()).getActionParameters();
final List<Object> parameter = convertActionParameter(resourceList, resource, jpaAction, actionParameter);
Annotatable r = null;
EdmType returnType = null;
if (resource.getAction().getReturnType() != null) {
returnType = resource.getAction().getReturnType().getType();
final Object result = jpaAction.getMethod().invoke(instance, parameter.toArray());
r = convertResult(result, returnType, jpaAction);
} else {
jpaAction.getMethod().invoke(instance, parameter.toArray());
}
if (serializer != null)
serializeResult(returnType, response, serializer.getContentType(), r, request);
else
response.setStatusCode(successStatusCode);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
} catch (InvocationTargetException | ODataException e) {
if (e.getCause() instanceof final ODataApplicationException cause) {
throw cause;
} else {
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
}
}
private List<Object> convertActionParameter(final List<UriResource> resourceList, final UriResourceAction resource,
final JPAAction jpaAction, final Map<String, org.apache.olingo.commons.api.data.Parameter> actionParameter)
throws ODataJPAModelException, ODataApplicationException {
final List<Object> parameter = new ArrayList<>();
final Parameter[] methodParameter = jpaAction.getMethod().getParameters();
for (int i = 0; i < methodParameter.length; i++) {
final Parameter declaredParameter = methodParameter[i];
if (i == 0 && resource.getAction().isBound()) {
parameter.add(createBindingParameter((UriResourceEntitySet) resourceList.get(resourceList.size() - 2))
.orElse(null));
} else {
// Any nullable parameter values not specified in the request MUST be assumed to have the null value.
// This is guaranteed by Olingo => no code needed
final String externalName = jpaAction.getParameter(declaredParameter).getName();
final org.apache.olingo.commons.api.data.Parameter param = actionParameter.get(externalName);
if (param != null)
parameter.add(JPAConversionHelper.convertParameter(param, sd));
else
parameter.add(null);
}
}
return parameter;
}
private Optional<Object> createBindingParameter(final UriResourceEntitySet entitySet) throws ODataJPAModelException,
ODataApplicationException {
final JPAEntityType et = sd.getEntity(entitySet.getType());
if (et != null) {
return new JPAInstanceCreator<>(odata, et).createInstance(entitySet.getKeyPredicates());
}
return Optional.empty();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/ODATARequestContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/ODATARequestContext.java | package com.sap.olingo.jpa.processor.core.processor;
import javax.annotation.Nonnull;
import org.apache.olingo.server.api.uri.UriInfo;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
interface ODATARequestContext {
/**
*
* @param uriInfo
* @throws ODataJPAIllegalAccessException In case UriInfo already exists e.g. because a page was provided
*/
void setUriInfo(@Nonnull final UriInfo uriInfo) throws ODataJPAIllegalAccessException;
void setJPASerializer(@Nonnull final JPASerializer serializer);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataEtagHelperImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataEtagHelperImpl.java | package com.sap.olingo.jpa.processor.core.processor;
import java.sql.Timestamp;
import java.util.Collection;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.etag.ETagHelper;
import org.apache.olingo.server.api.etag.PreconditionException;
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.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataEtagHelper;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
final class JPAODataEtagHelperImpl implements JPAODataEtagHelper {
private final ETagHelper olingoHelper;
JPAODataEtagHelperImpl(final OData odata) {
this.olingoHelper = odata.createETagHelper();
}
@Override
public boolean checkReadPreconditions(final String etag, final Collection<String> ifMatchHeaders,
final Collection<String> ifNoneMatchHeaders) throws PreconditionException {
return olingoHelper.checkReadPreconditions(etag, ifMatchHeaders, ifNoneMatchHeaders);
}
@Override
public void checkChangePreconditions(final String etag, final Collection<String> ifMatchHeaders,
final Collection<String> ifNoneMatchHeaders) throws PreconditionException {
olingoHelper.checkChangePreconditions(etag, ifMatchHeaders, ifNoneMatchHeaders);
}
@Override
public String asEtag(final JPAEntityType entityType, final Object value) throws ODataJPAQueryException {
try {
if (entityType.hasEtag()) {
final var etag = new StringBuilder();
if (value != null) {
if (entityType.getEtagValidator() == JPAEtagValidator.WEAK)
etag.append("W/");
etag.append("\"")
.append(value instanceof final Timestamp t ? t.toInstant().toString() : value.toString())
.append("\"");
}
return etag.toString();
}
return null;
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAAbstractRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAAbstractRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfoResource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
abstract class JPAAbstractRequestProcessor {
protected final EntityManager em;
protected final JPAServiceDocument sd;
protected final CriteriaBuilder cb;
protected final UriInfoResource uriInfo;
protected final JPASerializer serializer;
protected final OData odata;
protected final JPAServiceDebugger debugger;
protected int successStatusCode = HttpStatusCode.OK.getStatusCode();
protected final JPAODataRequestContextAccess requestContext;
JPAAbstractRequestProcessor(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
this.em = requestContext.getEntityManager();
this.cb = em.getCriteriaBuilder();
this.sd = requestContext.getEdmProvider().getServiceDocument();
this.uriInfo = requestContext.getUriInfo();
this.serializer = requestContext.getSerializer();
this.odata = odata;
this.debugger = requestContext.getDebugger();
this.requestContext = requestContext;
}
protected final void createSuccessResponse(final ODataResponse response, final ContentType responseFormat,
final SerializerResult serializerResult, @Nullable final JPAEntityCollectionExtension entityCollection) {
response.setContent(serializerResult.getContent());
response.setStatusCode(successStatusCode);
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
createETagHeader(response, entityCollection);
}
protected final void createNotModifiedResponse(final ODataResponse response,
final JPAEntityCollectionExtension entityCollection) {
response.setStatusCode(HttpStatusCode.NOT_MODIFIED.getStatusCode());
createETagHeader(response, entityCollection);
}
protected final void createPreconditionFailedResponse(final ODataResponse response) {
response.setStatusCode(HttpStatusCode.PRECONDITION_FAILED.getStatusCode());
}
private void createETagHeader(final ODataResponse response, final JPAEntityCollectionExtension entityCollection) {
if (entityCollection != null && entityCollection.hasSingleResult()) {
final var etag = entityCollection.getFirstResult().getETag();
if (etag != null)
response.setHeader(HttpHeader.ETAG, etag);
}
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAModifyUtil.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAModifyUtil.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ATTRIBUTE_NOT_FOUND;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.http.HttpStatusCode;
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.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys;
/**
* This class provides some primitive util methods to support modifying
* operations like create or update.
* <p>
* The set method shall fill an object from a given Map. JPA processor provides
* in a Map the internal, JAVA attribute, names. Based on the JAVA naming
* conventions the corresponding Setter is called, as long as the Setter has the
* correct type.
*
* @author Oliver Grande
*
*/
public final class JPAModifyUtil {
private static final Log LOGGER = LogFactory.getLog(JPAModifyUtil.class);
private JPAStructuredType st = null;
public String buildMethodNameSuffix(@Nonnull final JPAElement pathItem) {
final String relationName = pathItem.getInternalName();
return relationName.substring(0, 1).toUpperCase() + relationName.substring(1);
}
String buildSetterName(@Nonnull final JPAElement pathItem) {
return "set" + buildMethodNameSuffix(pathItem);
}
/**
* Creates a list of setter names from a list of {@link JPAAttribute}
* @param st
* @param pathItem
* @return
*/
Map<JPAAttribute, Method> buildSetterList(@Nonnull final Class<?> type,
@Nonnull final List<JPAAttribute> attributes) {
final Map<JPAAttribute, Method> result = new HashMap<>(attributes.size());
for (final JPAAttribute attribute : attributes) {
try {
result.put(attribute, type.getMethod(buildSetterName(attribute), attribute.getJavaType()));
} catch (NoSuchMethodException | SecurityException e) {
LOGGER.warn("Exception thrown while building setter list: " + e.getLocalizedMessage());
result.put(attribute, null);
}
}
return result;
}
/**
* Create a filled instance of a JPA entity key.
* <br>
* For JPA entities having only one key, so do not use an IdClass, the
* corresponding value in <code>jpaKeys</code> is returned
*
* @param et
* @param jpaKeys
* @param st
* @return
* @throws ODataJPAProcessorException
*/
public Object createPrimaryKey(final JPAEntityType et, final Map<String, Object> jpaKeys, final JPAStructuredType st)
throws ODataJPAProcessorException, ODataJPAInvocationTargetException {
try {
if (et.getKey().size() == 1)
return jpaKeys.get(et.getKey().get(0).getInternalName());
final Object key = et.getKeyType().getConstructor().newInstance();
setAttributes(jpaKeys, key, st);
return key;
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException | ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
*
* @param et
* @param instance
* @return
* @throws ODataJPAProcessorException
* @throws ODataJPAInvocationTargetException
*/
public Object createPrimaryKey(final JPAEntityType et, final Object instance) throws ODataJPAProcessorException {
try {
if (et.getKey().size() == 1)
return getAttribute(instance, et.getKey().get(0));
final Object key = et.getKeyType().getConstructor().newInstance();
for (final JPAAttribute keyElement : et.getKey()) {
setAttribute(key, keyElement, getAttribute(instance, keyElement));
}
return key;
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException | ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* Fills the key properties in instance. This is helpful e.g. for Upserts. <br>
* Setter for the key attributes are required.
* @param et Metadata describing the entity type
* @param jpaKeys Map of key properties
* @param instance Instance of the JPA entity to be filled
* @throws ODataJPAProcessorException
*/
public void setPrimaryKey(final JPAEntityType et, final Map<String, Object> jpaKeys, final Object instance)
throws ODataJPAProcessorException {
try {
if (et.hasEmbeddedKey()) {
final Object key = et.getKeyType().getConstructor().newInstance();
for (final JPAAttribute keyElement : et.getKey()) {
setAttribute(key, keyElement, jpaKeys.get(keyElement.getInternalName()));
}
final var setter = Arrays.stream(instance.getClass().getMethods())
.filter(method -> method.getParameterCount() == 1
&& method.getParameters()[0].getType() == et.getKeyType())
.findAny();
if (setter.isPresent()) {
setter.get().invoke(instance, key);
}
} else {
for (final var key : et.getKey()) {
setAttribute(instance, key, jpaKeys.get(key.getInternalName()));
}
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException | InstantiationException | ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* Sets a link between a source and target instance. Prerequisite are
* existing setter and getter on the level of the sourceInstance. In case of to n associations it is expected that the
* getter always returns a collection. In case structured properties are passed either a getter returns always an
* instance or the corresponding type has a parameter less constructor.
*
* @param parentInstance
* @param newInstance
* @param pathInfo
* @throws ODataJPAProcessorException
*/
public <T> void linkEntities(final Object sourceInstance, final T targetInstance, final JPAAssociationPath pathInfo)
throws ODataJPAProcessorException {
try {
final Object source = determineSourceForLink(sourceInstance, pathInfo);
setLink(source, targetInstance, pathInfo.getLeaf());
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* Fills instance without filling its embedded components.
*
* @param jpaAttributes Map of attributes and values that shall be changed
* @param instance JPA POJO instance to take the changes
* @param st Entity Type
* @throws ODataJPAProcessorException Thrown when ever a problem with invoking a getter or setter occurs except
* InvocationTargetException occurs.
* @throws ODataJPAInvocationTargetException Thrown when InvocationTargetException was thrown.
* ODataJPAInvocationTargetException contains the original cause and the OData path to the property which should be
* changed. The path starts with the entity type. The path parts a separated by {@code JPAPath.PATH_SEPERATOR}.
*/
public void setAttributes(final Map<String, Object> jpaAttributes, final Object instance, final JPAStructuredType st)
throws ODataJPAProcessorException, ODataJPAInvocationTargetException {
final Method[] methods = instance.getClass().getMethods();
for (final Method meth : methods) {
if (meth.getName().substring(0, 3).equals("set")) {
final String attributeName = meth.getName().substring(3, 4).toLowerCase(Locale.ENGLISH) + meth.getName()
.substring(4);
if (jpaAttributes.containsKey(attributeName)) {
final Object value = jpaAttributes.get(attributeName);
if (!(value instanceof Map<?, ?>) && !(value instanceof JPARequestEntity)) {
try {
final Class<?>[] parameters = meth.getParameterTypes();
if (parameters.length == 1 && (value == null || value.getClass() == parameters[0])) {
meth.invoke(instance, value);
}
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
} catch (final InvocationTargetException e) {
try {
throw new ODataJPAInvocationTargetException(e.getCause(),
st.getExternalName() + JPAPath.PATH_SEPARATOR + st.getAttribute(attributeName)
.orElseThrow(() -> new ODataJPAProcessorException(
ATTRIBUTE_NOT_FOUND, HttpStatusCode.INTERNAL_SERVER_ERROR, attributeName))
.getExternalName());
} catch (final ODataJPAModelException e1) {
throw new ODataJPAProcessorException(e1, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
}
}
}
}
/**
* Fills instance and its embedded components. In case of embedded
* components it first tries to get an existing instance. If that is non
* provided a new one is created and set.
*
* @param jpaAttributes Map of attributes and values that shall be changed
* @param instance JPA POJO instance to take the changes
* @param st Entity Type
* @throws ODataJPAProcessorException Thrown when ever a problem with invoking a getter or setter occurs except
* InvocationTargetException occurs.
* @throws ODataJPAInvocationTargetException Thrown when InvocationTargetException was thrown.
* ODataJPAInvocationTargetException contains the original cause and the OData path to the property which should be
* changed. The path starts with the entity type. The path parts a separated by {@code JPAPath.PATH_SEPERATOR}.
*/
public void setAttributesDeep(final Map<String, Object> jpaAttributes, final Object instance,
final JPAStructuredType st) throws ODataJPAProcessorException, ODataJPAInvocationTargetException {
final Method[] methods = instance.getClass().getMethods();
for (final Method meth : methods) {
if (meth.getName().substring(0, 3).equals("set")) {
final String attributeName = meth.getName().substring(3, 4).toLowerCase() + meth.getName().substring(4);
if (jpaAttributes.containsKey(attributeName)) {
final Object value = jpaAttributes.get(attributeName);
final Class<?>[] parameters = meth.getParameterTypes();
if (!(value instanceof JPARequestEntity) && parameters.length == 1) {
setAttributeDeep(instance, st, meth, attributeName, value, parameters);
}
}
}
}
}
/**
* Boxed
* missing getter
* @param parentInstance
* @param newInstance
* @param pathInfo
* @throws ODataJPAProcessorException
*/
public void setForeignKey(final Object parentInstance, final Object newInstance, final JPAAssociationPath pathInfo)
throws ODataJPAProcessorException {
try {
for (final JPAOnConditionItem joinColumn : pathInfo.getJoinColumnsList()) {
setAttribute(newInstance, joinColumn.getRightPath().getLeaf(), getAttribute(parentInstance, joinColumn
.getLeftPath().getLeaf()));
}
} catch (ODataJPAModelException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* Creates an instance of type <code>type</code> using a parameter free constructor
* @param type
* @return
* @throws NoSuchMethodException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private Object createInstance(final Class<?> type) throws NoSuchMethodException,
InstantiationException, IllegalAccessException, InvocationTargetException {
final Class<?>[] parameter = new Class<?>[0];
final Constructor<?> cons = type.getConstructor(parameter);
return cons.newInstance();
}
/**
* Determines the instance a link shall be added to. This may be the entity or a structured type. If the structured
* property does not exists, the method creates a new instance.
* @param sourceInstance
* @param pathInfo
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws ODataJPAProcessorException
*/
private Object determineSourceForLink(final Object sourceInstance, final JPAAssociationPath pathInfo)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ODataJPAProcessorException {
Object source = sourceInstance;
for (final JPAElement pathItem : pathInfo.getPath()) {
if (pathItem != pathInfo.getLeaf()) {
final String methodSuffix = buildMethodNameSuffix(pathItem);
final Method getter = source.getClass().getMethod("get" + methodSuffix);
Object next = getter.invoke(source);
if (next == null) {
try {
final Constructor<?> constructor = ((JPAAttribute) pathItem).getStructuredType().getTypeClass()
.getConstructor();
next = constructor.newInstance();
final Method setter = source.getClass().getMethod("set" + methodSuffix, next.getClass());
setter.invoke(source, next);
} catch (ODataJPAModelException | InstantiationException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
source = next;
}
}
return source;
}
/**
* Tries to read the current state of an attribute. If no getter exists an exception is thrown.
* @param instance
* @param attribute
* @return
* @throws NoSuchMethodException
* @throws ODataJPAProcessorException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private Object getAttribute(final Object instance, final JPAElement attribute) throws NoSuchMethodException,
ODataJPAProcessorException, IllegalAccessException, InvocationTargetException {
final Method getter = instance.getClass().getMethod("get" + buildMethodNameSuffix(attribute));
if (getter == null)
throw new ODataJPAProcessorException(MessageKeys.GETTER_NOT_FOUND, HttpStatusCode.INTERNAL_SERVER_ERROR,
buildMethodNameSuffix(attribute), instance.getClass().getName());
return getter.invoke(instance);
}
private void handleInvocationTargetException(final JPAStructuredType st, final String attributeName,
final Exception exception) throws ODataJPAInvocationTargetException, ODataJPAProcessorException {
String pathPart = null;
try {
pathPart = st.getAttribute(attributeName).orElseThrow(() -> new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND,
HttpStatusCode.INTERNAL_SERVER_ERROR, attributeName)).getExternalName();
if (this.st != null && this.st.equals(st)) {
final String path = st.getExternalName() + JPAPath.PATH_SEPARATOR + pathPart + JPAPath.PATH_SEPARATOR
+ ((ODataJPAInvocationTargetException) exception).getPath();
this.st = null;
throw new ODataJPAInvocationTargetException(exception.getCause(), path);
}
} catch (final ODataJPAModelException e1) {
throw new ODataJPAProcessorException(e1, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
if (exception instanceof final ODataJPAInvocationTargetException invocationTargetException)
throw new ODataJPAInvocationTargetException(exception.getCause(), pathPart + JPAPath.PATH_SEPARATOR
+ invocationTargetException.getPath());
else
throw new ODataJPAInvocationTargetException(exception.getCause(), pathPart);
}
/**
* Tries to read the current state of an attribute. If no getter exists null is returned.
* @param instance
* @param attribute
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private Object readCurrentState(final Object instance, final JPAElement attribute) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
final Method getter = instance.getClass().getMethod("get" + buildMethodNameSuffix(attribute));
if (getter == null)
return null;
return getter.invoke(instance);
}
private void setAttribute(final Object instance, final JPAElement attribute, final Object value)
throws NoSuchMethodException, ODataJPAProcessorException, IllegalAccessException, InvocationTargetException {
final Method setter = instance.getClass().getMethod("set" + buildMethodNameSuffix(attribute), value.getClass());
if (setter == null)
throw new ODataJPAProcessorException(MessageKeys.SETTER_NOT_FOUND, HttpStatusCode.INTERNAL_SERVER_ERROR,
buildMethodNameSuffix(attribute), instance.getClass().getName(), value.getClass().getName());
setter.invoke(instance, value);
}
private void setAttributeDeep(final Object instance, final JPAStructuredType st, final Method method,
final String attributeName, final Object value, final Class<?>[] parameters) throws ODataJPAProcessorException,
ODataJPAInvocationTargetException {
try {
final JPAAttribute attribute = st.getAttribute(attributeName).orElseThrow(
() -> new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND,
HttpStatusCode.INTERNAL_SERVER_ERROR, attributeName));
if (!attribute.isComplex() || value == null) {
if (value == null || parameters[0].isAssignableFrom(value.getClass())) {
method.invoke(instance, value);
}
} else if (attribute.isCollection()) {
setEmbeddedCollectionAttributeDeep(instance, st, method, value, parameters, attribute);
} else {
setEmbeddedAttributeDeep(instance, st, method, value, parameters, attribute);
}
} catch (IllegalAccessException | IllegalArgumentException | ODataJPAModelException
| NoSuchMethodException | SecurityException | InstantiationException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
} catch (InvocationTargetException | ODataJPAInvocationTargetException e) {
handleInvocationTargetException(st, attributeName, e);
}
}
@SuppressWarnings("unchecked")
private void setEmbeddedAttributeDeep(final Object instance, final JPAStructuredType st, final Method meth,
final Object value, final Class<?>[] parameters, final JPAAttribute attribute)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException,
ODataJPAModelException, ODataJPAProcessorException, ODataJPAInvocationTargetException {
Object embedded = readCurrentState(instance, attribute);
if (embedded == null) {
embedded = createInstance(parameters[0]);
meth.invoke(instance, embedded);
}
if (embedded != null) {
if (this.st == null)
this.st = st;
setAttributesDeep((Map<String, Object>) value, embedded, attribute.getStructuredType());
if (this.st.equals(st)) {
this.st = null;
}
}
}
@SuppressWarnings("unchecked")
private void setEmbeddedCollectionAttributeDeep(final Object instance, final JPAStructuredType st,
final Method method,
final Object value, final Class<?>[] parameters, final JPAAttribute attribute)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException,
ODataJPAModelException, ODataJPAProcessorException, ODataJPAInvocationTargetException {
Collection<Object> embedded = (Collection<Object>) readCurrentState(instance, attribute);
if (embedded == null) {
// List; Set; Queue
if (parameters[0].isAssignableFrom(List.class)) {
embedded = (Collection<Object>) createInstance(ArrayList.class);
} else {
embedded = (Collection<Object>) createInstance(parameters[0]);
}
method.invoke(instance, embedded);
}
if (embedded != null) {
if (this.st == null)
this.st = st;
embedded.clear();
for (final Map<String, Object> collectionElement : (Collection<Map<String, Object>>) value) {
final Object line = createInstance(attribute.getStructuredType().getTypeClass());
setAttributesDeep(collectionElement, line, attribute.getStructuredType());
embedded.add(line);
}
if (this.st.equals(st)) {
this.st = null;
}
}
}
@SuppressWarnings("unchecked")
private <T> void setLink(final Object sourceInstance, final T targetInstance, final JPAAssociationAttribute attribute)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ODataJPAProcessorException {
final String methodSuffix = attribute.getInternalName().substring(0, 1).toUpperCase() + attribute.getInternalName()
.substring(1);
if (attribute.isCollection()) {
final Method getter = sourceInstance.getClass().getMethod("get" + methodSuffix);
((Collection<T>) getter.invoke(sourceInstance)).add(targetInstance);
} else {
Method setter = null;
Class<?> clazz = targetInstance.getClass();
while (clazz != null && setter == null) {
try {
setter = sourceInstance.getClass().getMethod("set" + methodSuffix, clazz);
} catch (final NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
if (setter == null)
throw new ODataJPAProcessorException(MessageKeys.SETTER_NOT_FOUND, HttpStatusCode.INTERNAL_SERVER_ERROR, "set"
+ methodSuffix, sourceInstance.getClass().getName(), targetInstance.getClass().getName());
setter.invoke(sourceInstance, targetInstance);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAProcessorFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAProcessorFactory.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.QUERY_SERVER_DRIVEN_PAGING_GONE;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.QUERY_SERVER_DRIVEN_PAGING_NOT_IMPLEMENTED;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOption;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import com.sap.olingo.jpa.processor.core.api.JPAODataPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataPathInformation;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.query.JPACountQuery;
import com.sap.olingo.jpa.processor.core.query.JPAJoinCountQuery;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializerFactory;
import com.sap.olingo.jpa.processor.core.uri.JPAUriInfoFactory;
public final class JPAProcessorFactory {
private final JPAODataSessionContextAccess sessionContext;
private final JPASerializerFactory serializerFactory;
private final OData odata;
private final ServiceMetadata serviceMetadata;
public JPAProcessorFactory(final OData odata, final ServiceMetadata serviceMetadata,
final JPAODataSessionContextAccess context) {
super();
this.sessionContext = context;
this.serializerFactory = new JPASerializerFactory(odata, serviceMetadata, context);
this.odata = odata;
this.serviceMetadata = serviceMetadata;
}
public JPACUDRequestProcessor createCUDRequestProcessor(final UriInfo uriInfo, final ContentType responseFormat,
final JPAODataRequestContextAccess context, final Map<String, List<String>> header) throws ODataException {
final JPAODataRequestContextAccess requestContext = new JPAODataInternalRequestContext(uriInfo, serializerFactory
.createCUDSerializer(responseFormat, uriInfo, Optional.ofNullable(header.get(HttpHeader.ODATA_MAX_VERSION))),
context, header, null);
return new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, new JPAConversionHelper());
}
public JPACUDRequestProcessor createCUDRequestProcessor(final UriInfo uriInfo,
final JPAODataRequestContextAccess context, final Map<String, List<String>> header) throws ODataException {
final JPAODataRequestContextAccess requestContext = new JPAODataInternalRequestContext(uriInfo, context, header);
return new JPACUDRequestProcessor(odata, serviceMetadata, requestContext, new JPAConversionHelper());
}
public JPAActionRequestProcessor createActionProcessor(final UriInfo uriInfo, final ContentType responseFormat,
final Map<String, List<String>> header, final JPAODataRequestContextAccess context) throws ODataException {
final JPAODataRequestContextAccess requestContext = new JPAODataInternalRequestContext(uriInfo,
responseFormat != null ? serializerFactory.createSerializer(responseFormat, uriInfo, Optional.ofNullable(header
.get(HttpHeader.ODATA_MAX_VERSION))) : null, context, header, null);
return new JPAActionRequestProcessor(odata, requestContext);
}
public JPARequestProcessor createProcessor(final UriInfo uriInfo, final ContentType responseFormat,
final Map<String, List<String>> header, final JPAODataRequestContextAccess context,
final JPAODataPathInformation pathInformation) throws ODataException {
final var page = getPage(header, uriInfo, context, pathInformation);
final var newUriInfo = new JPAUriInfoFactory(page).build();
final JPAODataRequestContextAccess requestContext = new JPAODataInternalRequestContext(newUriInfo, serializerFactory
.createSerializer(responseFormat, newUriInfo, Optional.ofNullable(header.get(
HttpHeader.ODATA_MAX_VERSION))), context, header, pathInformation);
return switch (newUriInfo.getLastResourcePart().getKind()) {
case count -> new JPACountRequestProcessor(odata, requestContext);
case function -> {
checkFunctionPathSupported(newUriInfo.getUriResourceParts());
yield new JPAFunctionRequestProcessor(odata, requestContext);
}
case complexProperty, primitiveProperty, navigationProperty, entitySet, singleton, value -> {
checkNavigationPathSupported(newUriInfo.getUriResourceParts());
yield new JPANavigationRequestProcessor(odata, serviceMetadata, requestContext);
}
default -> throw new ODataJPAProcessorException(
ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_RESOURCE_TYPE,
HttpStatusCode.NOT_IMPLEMENTED, newUriInfo.getLastResourcePart().getKind().toString());
};
}
private void checkFunctionPathSupported(final List<UriResource> resourceParts) throws ODataApplicationException {
if (resourceParts.size() > 2)
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_FUNC_WITH_NAVI,
HttpStatusCode.NOT_IMPLEMENTED);
}
private void checkNavigationPathSupported(final List<UriResource> resourceParts) throws ODataApplicationException {
for (final UriResource resourceItem : resourceParts) {
if (resourceItem.getKind() != UriResourceKind.complexProperty
&& resourceItem.getKind() != UriResourceKind.primitiveProperty
&& resourceItem.getKind() != UriResourceKind.navigationProperty
&& resourceItem.getKind() != UriResourceKind.entitySet
&& resourceItem.getKind() != UriResourceKind.singleton
&& resourceItem.getKind() != UriResourceKind.value)
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_RESOURCE_TYPE,
HttpStatusCode.NOT_IMPLEMENTED, resourceItem.getKind().toString());
}
}
@Nonnull
private JPAODataPage getPage(final Map<String, List<String>> headers, final UriInfo uriInfo,
final JPAODataRequestContextAccess requestContext, final JPAODataPathInformation pathInformation)
throws ODataException {
final var page = new JPAODataPage(uriInfo, 0, Integer.MAX_VALUE, null);
// Server-Driven-Paging
if (serverDrivenPaging(uriInfo)) {
final var skipToken = skipToken(uriInfo);
if (skipToken != null && !skipToken.isEmpty()) {
return sessionContext.getPagingProvider().getNextPage(skipToken, odata,
odata.createServiceMetadata(requestContext.getEdmProvider(), requestContext.getEdmProvider()
.getReferences()), requestContext.getRequestParameter(), requestContext.getEntityManager())
.orElseThrow(() -> new ODataJPAProcessorException(QUERY_SERVER_DRIVEN_PAGING_GONE, HttpStatusCode.GONE,
skipToken));
} else {
final JPACountQuery countQuery = new JPAJoinCountQuery(odata, new JPAODataInternalRequestContext(uriInfo,
requestContext, headers));
final var preferredPageSize = getPreferredPageSize(headers);
return sessionContext.getPagingProvider().getFirstPage(
requestContext.getRequestParameter(), pathInformation, uriInfo, preferredPageSize, countQuery,
requestContext.getEntityManager())
.orElse(page);
}
}
return page;
}
private Integer getPreferredPageSize(final Map<String, List<String>> headers) throws ODataJPAProcessorException {
final var preferredHeaders = getHeader("Prefer", headers);
if (preferredHeaders != null) {
for (final String header : preferredHeaders) {
if (header.startsWith("odata.maxpagesize")) {
try {
return Integer.valueOf((header.split("=")[1]));
} catch (final NumberFormatException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.BAD_REQUEST);
}
}
}
}
return null;
}
private boolean serverDrivenPaging(final UriInfo uriInfo) throws ODataJPAProcessorException {
for (final SystemQueryOption option : uriInfo.getSystemQueryOptions()) {
if (option.getKind() == SystemQueryOptionKind.SKIPTOKEN
&& sessionContext.getPagingProvider() == null)
throw new ODataJPAProcessorException(QUERY_SERVER_DRIVEN_PAGING_NOT_IMPLEMENTED,
HttpStatusCode.NOT_IMPLEMENTED);
}
final var resourceParts = uriInfo.getUriResourceParts();
return sessionContext.getPagingProvider() != null
&& resourceParts.get(resourceParts.size() - 1).getKind() != UriResourceKind.function;
}
private String skipToken(final UriInfo uriInfo) {
for (final SystemQueryOption option : uriInfo.getSystemQueryOptions()) {
if (option.getKind() == SystemQueryOptionKind.SKIPTOKEN)
return option.getText();
}
return null;
}
private List<String> getHeader(final String name, final Map<String, List<String>> headers) {
for (final Entry<String, List<String>> header : headers.entrySet()) {
if (header.getKey().equalsIgnoreCase(name)) {
return header.getValue();
}
}
return Collections.emptyList();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAFunctionRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAFunctionRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.FUNCTION_UNKNOWN;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctionType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaFunction;
import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
/**
* Functions as User Defined Functions, Native Query, as Criteria Builder does not provide the option to used UDFs in
* the From clause.
* @author Oliver Grande
*
*/
public final class JPAFunctionRequestProcessor extends JPAOperationRequestProcessor implements JPARequestProcessor { // NOSONAR
private final JPAODataDatabaseProcessor dbProcessor;
public JPAFunctionRequestProcessor(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
this.dbProcessor = requestContext.getDatabaseProcessor();
}
@Override
public void retrieveData(final ODataRequest request, final ODataResponse response, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
final UriResourceFunction uriResourceFunction =
(UriResourceFunction) uriInfo.getUriResourceParts().get(uriInfo.getUriResourceParts().size() - 1);
final JPAFunction jpaFunction = sd.getFunction(uriResourceFunction.getFunction());
if (jpaFunction == null)
throw new ODataJPAProcessorException(FUNCTION_UNKNOWN, HttpStatusCode.BAD_REQUEST, uriResourceFunction
.getFunction().getName());
Object result = null;
if (jpaFunction.getFunctionType() == EdmFunctionType.JavaClass) {
result = new JPAJavaFunctionProcessor(sd, uriResourceFunction, (JPAJavaFunction) jpaFunction,
em, requestContext.getHeader(), requestContext.getRequestParameter()).process();
} else if (jpaFunction.getFunctionType() == EdmFunctionType.UserDefinedFunction) {
result = dbProcessor.executeFunctionQuery(uriInfo.getUriResourceParts(), (JPADataBaseFunction) jpaFunction, em,
requestContext.getHeader(), requestContext.getRequestParameter());
}
final EdmType returnType = uriResourceFunction.getFunction().getReturnType().getType();
final Annotatable annotatable = convertResult(result, returnType, jpaFunction);
serializeResult(returnType, response, responseFormat, annotatable, request);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestEntity.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestEntity.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPATopLevelEntity;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
/**
* Representing an entity that should be created, updated or deleted by a POST, PUT, PATCH or DELETE request
* @author Oliver Grande
*
*/
public interface JPARequestEntity {
/**
* Returns all OData request header
* @return an unmodifiable Map of header names/values
*/
public Map<String, List<String>> getAllHeader();
/**
* For the creation of a dependent entity an instance of the requested entity (root entity) is provided. <br>
* The
* instance must not be merged
* @return
*/
public Optional<Object> getBeforeImage();
/**
* Provides the given claims of a user
* @return
*/
public Optional<JPAODataClaimProvider> getClaims();
/**
* List of attributes with pojo attributes name converted into JAVA types. In case the entity contains embedded
* attributes these are given as maps themselves.
* <p>
* @return
*/
public Map<String, Object> getData();
/**
* Provides an instance of the entity metadata
* @return
*/
public JPAEntityType getEntityType();
/**
* Provides an instance to access the Singleton or Entity Set metadata
* @return
*/
public Optional<JPATopLevelEntity> getTopLevelEntity();
/**
* Returns a list of given filed groups
* @return
*/
public List<String> getGroups();
/**
* Contains the key attributes of the entity to be update or deleted. Returns an empty Map in case of create.
* @return
*/
public Map<String, Object> getKeys();
/**
* Returns an instance utility service
* @return
*/
public JPAModifyUtil getModifyUtil();
/**
* <a href=
* "https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752299">
* 11.4.2.2 Create Related Entities When Creating an Entity</a>
* @return
*/
public Map<JPAAssociationPath, List<JPARequestEntity>> getRelatedEntities();
/**
* <a href=
* "https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752299">
* 11.4.2.1 Link to Related Entities When Creating an Entity</a>
* @return
*/
public Map<JPAAssociationPath, List<JPARequestLink>> getRelationLinks();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAEmptyDebugger.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAEmptyDebugger.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.server.api.debug.RuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
public final class JPAEmptyDebugger implements JPAServiceDebugger {
@Override
public List<RuntimeMeasurement> getRuntimeInformation() {
return new ArrayList<>();
}
@Override
public JPARuntimeMeasurement newMeasurement(final Object instance, final String methodName) {
return new JPAEmptyMeasurement();
}
public static class JPAEmptyMeasurement implements JPARuntimeMeasurement {
@Override
public void close() {
// DO Nothing
}
@Override
public long getMemoryConsumption() {
return 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/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataInternalRequestContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataInternalRequestContext.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.NO_METADATA_PROVIDER;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
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.UriInfoResource;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
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.JPAEntityType;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataDefaultTransactionFactory;
import com.sap.olingo.jpa.processor.core.api.JPAODataEtagHelper;
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.JPAODataPathInformation;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory;
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.ODataJPAIllegalAccessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.query.ExpressionUtility;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
public final class JPAODataInternalRequestContext implements JPAODataRequestContextAccess,
ODATARequestContext {
private Optional<JPAODataClaimProvider> claims;
private Optional<JPAODataGroupProvider> groups;
private EntityManager em;
private UriInfoResource uriInfo;
private JPASerializer serializer;
private JPACUDRequestHandler cudRequestHandler;
private JPAServiceDebugger debugger;
private JPADebugSupportWrapper debugSupport;
private JPAODataTransactionFactory transactionFactory;
private final JPAHttpHeaderMap header;
private JPARequestParameterMap customParameter;
private List<Locale> locales;
private final JPAHookFactory hookFactory;
private JPAODataDatabaseProcessor dbProcessor;
private Optional<JPAEdmProvider> edmProvider;
private JPAODataDatabaseOperations operationConverter;
private JPAODataQueryDirectives queryDirectives;
private JPAODataEtagHelper etagHelper;
private Optional<JPAODataPagingProvider> pagingProvider;
private JPAODataPathInformation pathInformation;
private String mappingPath;
public JPAODataInternalRequestContext(@Nonnull final JPAODataRequestContext requestContext,
@Nonnull final JPAODataSessionContextAccess sessionContext, final OData odata) {
this.header = new JPAHttpHeaderHashMap(Collections.emptyMap());
copyRequestContext(requestContext, sessionContext);
this.hookFactory = new JPAHookFactory(em, header, customParameter);
initDebugger();
etagHelper = new JPAODataEtagHelperImpl(odata);
}
/**
* Copy constructor only using new uri info
* @param uriInfo
* @param context
* @throws ODataJPAProcessorException
*/
public JPAODataInternalRequestContext(final UriInfoResource uriInfo, final JPAODataRequestContextAccess context)
throws ODataJPAProcessorException {
this(uriInfo, null, context, context.getHeader(), null);
}
/**
* Copy constructor switching also the header
* @param uriInfo
* @param context
* @throws ODataJPAProcessorException
*/
public JPAODataInternalRequestContext(final UriInfoResource uriInfo, final JPAODataRequestContextAccess context,
final Map<String, List<String>> header) throws ODataJPAProcessorException {
this(uriInfo, null, context, header, null);
}
JPAODataInternalRequestContext(final UriInfoResource uriInfo, @Nullable final JPASerializer serializer,
final JPAODataRequestContextAccess context, final Map<String, List<String>> header,
final JPAODataPathInformation pathInformation)
throws ODataJPAProcessorException {
copyContextValues(context);
this.serializer = serializer;
this.cudRequestHandler = this.cudRequestHandler == null ? new JPADefaultCUDRequestHandler()
: this.cudRequestHandler;
this.uriInfo = uriInfo;
this.header = new JPAHttpHeaderHashMap(header);
this.customParameter = new JPARequestParameterHashMap(context.getRequestParameter());
this.hookFactory = new JPAHookFactory(em, this.header, customParameter);
this.pathInformation = pathInformation != null ? pathInformation : this.pathInformation;
}
@Override
public Optional<EdmTransientPropertyCalculator<?>> getCalculator(@Nonnull final JPAAttribute transientProperty)
throws ODataJPAProcessorException {
return hookFactory.getTransientPropertyCalculator(transientProperty);
}
@Override
public Optional<EdmQueryExtensionProvider> getQueryEnhancement(final JPAEntityType et)
throws ODataJPAProcessorException {
return hookFactory.getQueryExtensionProvider(et);
}
@Override
public Optional<JPAODataClaimProvider> getClaimsProvider() {
return claims;
}
@Override
public JPACUDRequestHandler getCUDRequestHandler() {
return cudRequestHandler;
}
@Override
public JPAServiceDebugger getDebugger() {
if (debugger == null)
initDebugger();
return debugger;
}
public JPADebugSupportWrapper getDebugSupport() {
if (debugger == null)
initDebugger();
return debugSupport;
}
@Override
public EntityManager getEntityManager() {
return this.em;
}
@Override
public Optional<JPAODataGroupProvider> getGroupsProvider() {
return groups;
}
@Override
public JPAHttpHeaderMap getHeader() {
return header;
}
@Override
public JPARequestParameterMap getRequestParameter() {
return customParameter;
}
@Override
public JPASerializer getSerializer() {
return serializer;
}
@Override
public JPAODataTransactionFactory getTransactionFactory() {
if (transactionFactory == null && em != null)
createDefaultTransactionFactory();
return this.transactionFactory;
}
@Override
public UriInfoResource getUriInfo() {
return this.uriInfo;
}
@Override
public Locale getLocale() {
if (locales == null || locales.isEmpty())
return ExpressionUtility.determineFallbackLocale(header);
return locales.get(0);
}
@Override
public List<Locale> getProvidedLocale() {
return locales;
}
@Override
public JPAODataEtagHelper getEtagHelper() {
return etagHelper;
}
@Override
public void setJPASerializer(@Nonnull final JPASerializer serializer) {
this.serializer = Objects.requireNonNull(serializer);
}
@Override
public void setUriInfo(@Nonnull final UriInfo uriInfo) throws ODataJPAIllegalAccessException {
if (this.uriInfo != null)
throw new ODataJPAIllegalAccessException();
this.uriInfo = Objects.requireNonNull(uriInfo);
}
@Override
public JPAODataDatabaseProcessor getDatabaseProcessor() {
return dbProcessor;
}
@Override
public JPAEdmProvider getEdmProvider() throws ODataJPAProcessorException {
return edmProvider.orElseThrow(
() -> new ODataJPAProcessorException(NO_METADATA_PROVIDER, INTERNAL_SERVER_ERROR));
}
@Override
public JPAODataDatabaseOperations getOperationConverter() {
return operationConverter;
}
@Override
public JPAODataQueryDirectives getQueryDirectives() {
return queryDirectives;
}
@Override
public Optional<JPAODataPagingProvider> getPagingProvider() {
return pagingProvider;
}
@Override
public JPAODataPathInformation getPathInformation() {
return pathInformation;
}
@Override
public String getMappingPath() {
return mappingPath;
}
private void copyContextValues(final JPAODataRequestContextAccess context)
throws ODataJPAProcessorException {
this.em = context.getEntityManager();
this.claims = context.getClaimsProvider();
this.groups = context.getGroupsProvider();
this.cudRequestHandler = context.getCUDRequestHandler();
this.transactionFactory = context.getTransactionFactory();
this.locales = context.getProvidedLocale();
this.debugSupport = context instanceof final JPAODataInternalRequestContext internalContext
? internalContext.getDebugSupport() : null;
this.dbProcessor = context.getDatabaseProcessor();
this.edmProvider = Optional.ofNullable(context.getEdmProvider());
this.operationConverter = context.getOperationConverter();
this.queryDirectives = context.getQueryDirectives();
this.etagHelper = context.getEtagHelper();
this.pagingProvider = context.getPagingProvider();
this.pathInformation = context.getPathInformation();
}
private void copyRequestContext(@Nonnull final JPAODataRequestContext requestContext,
@Nonnull final JPAODataSessionContextAccess sessionContext) {
final var version = sessionContext.getApiVersion(requestContext.getVersion());
em = determineEntityManager(requestContext, version);
claims = requestContext.getClaimsProvider();
groups = requestContext.getGroupsProvider();
cudRequestHandler = requestContext.getCUDRequestHandler();
debugSupport = requestContext.getDebuggerSupport() != null
? new JPADebugSupportWrapper(requestContext.getDebuggerSupport())
: null;
transactionFactory = requestContext.getTransactionFactory();
locales = requestContext.getLocales();
customParameter = requestContext.getRequestParameter() != null
? requestContext.getRequestParameter()
: new JPARequestParameterHashMap();
dbProcessor = sessionContext.getDatabaseProcessor();
operationConverter = sessionContext.getOperationConverter();
edmProvider = determineEdmProvider(version, sessionContext, em);
queryDirectives = sessionContext.getQueryDirectives();
pagingProvider = Optional.ofNullable(sessionContext.getPagingProvider());
mappingPath = version != null
? version.getMappingPath()
: null;
}
private EntityManager determineEntityManager(final JPAODataRequestContext requestContext,
final JPAODataApiVersionAccess version) {
return requestContext.getEntityManager() != null
? requestContext.getEntityManager()
: createEntityManager(version);
}
private EntityManager createEntityManager(final JPAODataApiVersionAccess version) {
return version != null
? version.getEntityManagerFactory().createEntityManager()
: null;
}
private Optional<JPAEdmProvider> determineEdmProvider(final JPAODataApiVersionAccess apiVersion,
final JPAODataSessionContextAccess sessionContext, final EntityManager em) {
try {
if (apiVersion == null) {
if (em != null
&& sessionContext instanceof final JPAODataServiceContext context)
return Optional.of(asUserGroupRestricted(context.getEdmProvider(em)));
return Optional.empty();
}
return Optional.ofNullable(asUserGroupRestricted(apiVersion.getEdmProvider()));
} catch (final ODataException e) {
debugger.debug(this, Arrays.toString(e.getStackTrace()));
return Optional.empty();
}
}
private JPAEdmProvider asUserGroupRestricted(final JPAEdmProvider unrestricted) {
if (unrestricted != null)
return groups.map(JPAODataGroupProvider::getGroups)
.map(unrestricted::asUserGroupRestricted)
.orElse(unrestricted);
return null;
}
private void createDefaultTransactionFactory() {
this.transactionFactory = new JPAODataDefaultTransactionFactory(em);
}
private void initDebugger() {
// see org.apache.olingo.server.core.debug.ServerCoreDebugger
debugger = new JPAEmptyDebugger();
if (debugSupport != null) {
debugger = new JPACoreDebugger(debugSupport.isUserAuthorized());
debugSupport.addDebugger(debugger);
}
}
private static class JPADefaultCUDRequestHandler extends JPAAbstractCUDRequestHandler {
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestEntityImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestEntityImpl.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPATopLevelEntity;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataGroupProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
final class JPARequestEntityImpl implements JPARequestEntity {
private static final JPAModifyUtil utility = new JPAModifyUtil();
private final JPAEntityType et;
private final Map<String, Object> jpaAttributes;
private final Map<String, Object> jpaKeys;
private final Map<JPAAssociationPath, List<JPARequestEntity>> jpaDeepEntities;
private final Map<JPAAssociationPath, List<JPARequestLink>> jpaLinks;
private final Map<String, List<String>> odataHeaders;
private Optional<Object> beforeImage;
private final JPAODataRequestContextAccess requestContext;
private final Optional<JPATopLevelEntity> topLevel;
JPARequestEntityImpl(
final Optional<JPATopLevelEntity> topLevel,
final JPAEntityType et,
final Map<String, Object> jpaAttributes,
final Map<JPAAssociationPath, List<JPARequestEntity>> jpaDeepEntities,
final Map<JPAAssociationPath, List<JPARequestLink>> jpaLinks, final Map<String, Object> keys,
final Map<String, List<String>> headers, final JPAODataRequestContextAccess requestContext) {
super();
this.topLevel = topLevel;
this.et = et;
this.jpaAttributes = jpaAttributes;
this.jpaDeepEntities = jpaDeepEntities;
this.jpaLinks = jpaLinks;
this.jpaKeys = keys;
this.odataHeaders = headers;
this.requestContext = requestContext;
}
@Override
public Map<String, List<String>> getAllHeader() {
return odataHeaders;
}
@Override
public Optional<Object> getBeforeImage() {
return beforeImage;
}
@Override
public Optional<JPAODataClaimProvider> getClaims() {
return requestContext.getClaimsProvider();
}
@Override
public Map<String, Object> getData() {
return jpaAttributes;
}
@Override
public JPAEntityType getEntityType() {
return et;
}
@Override
public Map<String, Object> getKeys() {
return jpaKeys;
}
@Override
public JPAModifyUtil getModifyUtil() {
return utility;
}
@Override
public Map<JPAAssociationPath, List<JPARequestEntity>> getRelatedEntities() {
return jpaDeepEntities;
}
@Override
public Map<JPAAssociationPath, List<JPARequestLink>> getRelationLinks() {
return jpaLinks;
}
void setBeforeImage(final Optional<Object> beforeImage) {
this.beforeImage = beforeImage;
}
@Override
public List<String> getGroups() {
final Optional<JPAODataGroupProvider> provider = requestContext.getGroupsProvider();
return provider.isPresent() ? provider.get().getGroups() : Collections.emptyList();
}
@Override
public Optional<JPATopLevelEntity> getTopLevelEntity() {
return topLevel;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPANavigationRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPANavigationRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ODATA_MAXPAGESIZE_NOT_A_NUMBER;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.QUERY_PREPARATION_ERROR;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.VALIDATION_NOT_POSSIBLE_TOO_MANY_RESULTS;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.Tuple;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.data.ComplexValue;
import org.apache.olingo.commons.api.data.EntityCollection;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.etag.PreconditionException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourcePartTyped;
import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.converter.JPATupleRowConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPANotImplementedException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.query.JPACollectionItemInfo;
import com.sap.olingo.jpa.processor.core.query.JPACollectionJoinQuery;
import com.sap.olingo.jpa.processor.core.query.JPAConvertibleResult;
import com.sap.olingo.jpa.processor.core.query.JPAExpandItemInfo;
import com.sap.olingo.jpa.processor.core.query.JPAExpandItemInfoFactory;
import com.sap.olingo.jpa.processor.core.query.JPAExpandQueryFactory;
import com.sap.olingo.jpa.processor.core.query.JPAJoinCountQuery;
import com.sap.olingo.jpa.processor.core.query.JPAJoinQuery;
import com.sap.olingo.jpa.processor.core.query.JPAKeyBoundary;
import com.sap.olingo.jpa.processor.core.query.JPANavigationPropertyInfo;
import com.sap.olingo.jpa.processor.core.query.Utility;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
public final class JPANavigationRequestProcessor extends JPAAbstractGetRequestProcessor {
private static final Log LOGGER = LogFactory.getLog(JPANavigationRequestProcessor.class);
private final ServiceMetadata serviceMetadata;
private final UriResource lastItem;
public JPANavigationRequestProcessor(final OData odata, final ServiceMetadata serviceMetadata,
final JPAODataRequestContextAccess requestContext) throws ODataException {
super(odata, requestContext);
this.serviceMetadata = serviceMetadata;
final var resourceParts = uriInfo.getUriResourceParts();
this.lastItem = resourceParts.get(resourceParts.size() - 1);
}
@Override
public <K extends Comparable<K>> void retrieveData(final ODataRequest request, final ODataResponse response,
final ContentType responseFormat) throws ODataException {
try (var measurement = debugger.newMeasurement(this, "retrieveData")) {
checkRequestSupported();
// Create a JPQL Query and execute it
JPAJoinQuery query = null;
try {
query = new JPAJoinQuery(odata, requestContext);
} catch (final ODataException e) {
throw new ODataJPAProcessorException(QUERY_PREPARATION_ERROR, HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
final var result = query.execute();
// Validate If-Match and If-None-Match headers
final var conditionValidationResult = validateEntityTag(result, requestContext.getHeader());
// Read Expand and Collection
JPAEntityCollectionExtension entityCollection;
if (conditionValidationResult == JPAETagValidationResult.SUCCESS && !isRootResultEmpty(result)) {
final var keyBoundary = result.getKeyBoundary(requestContext, query.getNavigationInfo());
final var watchDog = new JPAExpandWatchDog(determineTargetEntitySet(requestContext));
watchDog.watch(uriInfo.getExpandOption(), uriInfo.getUriResourceParts());
result.putChildren(readExpandEntities(request.getAllHeaders(), query.getNavigationInfo(), uriInfo, keyBoundary,
watchDog));
}
// Convert tuple result into an OData Result
try (var converterMeasurement = debugger.newMeasurement(this, "convertResult")) {
entityCollection = result.asEntityCollection(new JPATupleRowConverter(
((JPAExpandResult) result).getEntityType(), sd, odata.createUriHelper(), serviceMetadata, requestContext))
.get(ROOT_RESULT_KEY);
} catch (final ODataApplicationException e) {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.QUERY_RESULT_CONV_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
// Set Next Link
entityCollection.setNext(buildNextLink(uriInfo));
// Count results if requested
final var countOption = uriInfo.getCountOption();
if (countOption != null && countOption.getValue())
entityCollection.setCount(new JPAJoinCountQuery(odata, requestContext)
.countResults().intValue());
/*
* See part 1:
* - 9.1.1 Response Code 200 OK: A request that does not create a resource returns 200 OK if it is completed
* successfully and the value of the resource is not null. In this case, the response body MUST contain the value
* of the resource specified in the request URL.
* - 9.2.1 Response Code 404 Not Found: 404 Not Found indicates that the resource specified by the request URL
* does not exist. The response body MAY provide additional information.
* - 11.2.1 Requesting Individual Entities:
* -- If no entity exists with the key values specified in the request URL, the service responds with 404 Not
* Found.
* - 11.2.3 Requesting Individual Properties:
* -- If the property is single-valued and has the null value, the service responds with 204 No Content.
* -- If the property is not available, for example due to permissions, the service responds with 404 Not Found.
* - 11.2.6 Requesting Related Entities:
* -- If the navigation property does not exist on the entity indicated by the request URL, the service returns
* 404
* Not Found.
* -- If the relationship terminates on a collection, the response MUST be the format-specific representation of
* the
* collection of related entities. If no entities are related, the response is the format-specific representation
* of
* an empty collection.
* -- If the relationship terminates on a single entity, the response MUST be the format-specific representation
* of
* the related single entity. If no entity is related, the service returns 204 No Content.
*/
if (conditionValidationResult == JPAETagValidationResult.NOT_MODIFIED)
createNotModifiedResponse(response, entityCollection);
else if (conditionValidationResult == JPAETagValidationResult.PRECONDITION_FAILED)
createPreconditionFailedResponse(response);
else if (hasNoContent(entityCollection))
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
else if (doesNotExists(entityCollection.hasResults()))
response.setStatusCode(HttpStatusCode.NOT_FOUND.getStatusCode());
// 200 OK indicates that either a result was found or that the a Entity Collection query had no result
else if (((EntityCollection) entityCollection).getEntities() != null) {
try (var serializerMeasurement = debugger.newMeasurement(this, "serialize")) {
final var serializerResult = serializer.serialize(request, entityCollection);
createSuccessResponse(response, responseFormat, serializerResult, entityCollection);
}
} else {
// A request returns 204 No Content if the requested resource has the null value, or if the service applies a
// return=minimal preference. In this case, the response body MUST be empty.
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
}
}
void checkRequestSupported() throws ODataJPAProcessException {
if (uriInfo.getApplyOption() != null)
throw new ODataJPANotImplementedException("$apply");
}
/**
* Validate
* <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-14.24">If-Match</a> and
* <a href="https://datatracker.ietf.org/doc/html/rfc2616#section-14.26">If-None-Match</a>
* headers
* @param result Query result
* @param header List of all request headers
* @throws ODataJPAProcessorException
*/
JPAETagValidationResult validateEntityTag(final JPAConvertibleResult result, final JPAHttpHeaderMap header)
throws ODataJPAProcessorException {
try {
if (result instanceof final JPAExpandResult expandResult) {
if (expandResult.getEntityType().hasEtag()) {
final var results = expandResult.getResult(ROOT_RESULT_KEY);
final var ifNoneMatchEntityTags = getMatchHeader(header, HttpHeader.IF_NONE_MATCH);
final var ifMatchEntityTags = getMatchHeader(header, HttpHeader.IF_MATCH);
if (results.size() == 1) {
final var etagAlias = expandResult.getEntityType().getEtagPath().getAlias();
final var etag = requestContext.getEtagHelper().asEtag(expandResult.getEntityType(),
results.get(0).get(etagAlias));
if (requestContext.getEtagHelper().checkReadPreconditions(etag, ifMatchEntityTags, ifNoneMatchEntityTags))
return JPAETagValidationResult.NOT_MODIFIED;
} else if (!preconditionCheckSupported(results, ifNoneMatchEntityTags, ifMatchEntityTags)) {
throw new ODataJPAProcessorException(VALIDATION_NOT_POSSIBLE_TOO_MANY_RESULTS,
HttpStatusCode.BAD_REQUEST);
}
}
} else {
LOGGER.warn("Result is not of type JPAExpandResult. ETag validation not possible");
}
} catch (final ODataJPAModelException | ODataJPAQueryException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
catch (final PreconditionException e) {
return JPAETagValidationResult.PRECONDITION_FAILED;
}
return JPAETagValidationResult.SUCCESS;
}
private boolean isRootResultEmpty(final JPAConvertibleResult result) {
if (result instanceof final JPAExpandResult expandResult) {
return expandResult.getResult(ROOT_RESULT_KEY).isEmpty();
}
return false;
}
private List<String> getMatchHeader(final JPAHttpHeaderMap headers, final String matchHeader) {
return Optional.ofNullable(headers.get(matchHeader)).orElseGet(() -> headers.get(
matchHeader.toLowerCase(Locale.ENGLISH)));
}
private boolean preconditionCheckSupported(final List<Tuple> results, final List<String> ifNoneMatchEntityTags,
final List<String> ifMatchEntityTags) {
return results.size() <= 1
|| (isEmpty(ifMatchEntityTags) && isEmpty(ifNoneMatchEntityTags));
}
private boolean isEmpty(final List<String> list) {
return list == null || list.isEmpty();
}
private URI buildNextLink(final UriInfoResource uriInfo) throws ODataJPAProcessorException {
if (uriInfo != null && uriInfo.getSkipTokenOption() != null) {
try {
final var skipToken = uriInfo.getSkipTokenOption().getValue();
return new URI(Utility.determineBindingTarget(uriInfo.getUriResourceParts()).getName() + "?"
+ SystemQueryOptionKind.SKIPTOKEN.toString() + "=" + skipToken);
} catch (final URISyntaxException e) {
throw new ODataJPAProcessorException(ODATA_MAXPAGESIZE_NOT_A_NUMBER, HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
return null;
}
private boolean complexHasNoContent(final JPAEntityCollectionExtension entityCollection) {
final String name;
if (!entityCollection.hasResults())
return false;
name = Utility.determineStartNavigationPath(uriInfo.getUriResourceParts()).getProperty().getName();
final var property = entityCollection.getFirstResult().getProperty(name);
if (property != null) {
for (final Property p : ((ComplexValue) property.getValue()).getValue()) {
if (p.getValue() != null) {
return false;
}
}
}
return true;
}
private boolean doesNotExists(final boolean hasResults) throws ODataApplicationException {
// handle ../Organizations('xx')
return (!hasResults
&& ((lastItem.getKind() == UriResourceKind.primitiveProperty
|| lastItem.getKind() == UriResourceKind.complexProperty
|| lastItem.getKind() == UriResourceKind.entitySet
&& !Utility.determineKeyPredicates(lastItem).isEmpty())
|| lastItem.getKind() == UriResourceKind.singleton));
}
private boolean hasNoContent(final JPAEntityCollectionExtension entityCollection) {
if (lastItem.getKind() == UriResourceKind.primitiveProperty
|| lastItem.getKind() == UriResourceKind.navigationProperty
|| lastItem.getKind() == UriResourceKind.complexProperty) {
if (((UriResourcePartTyped) this.lastItem).isCollection()) {
// Collections always return 200 no matter if type are empty or not
return false;
}
if (lastItem.getKind() == UriResourceKind.primitiveProperty) {
return primitiveHasNoContent(entityCollection);
}
if (lastItem.getKind() == UriResourceKind.complexProperty) {
return complexHasNoContent(entityCollection);
}
return !entityCollection.hasResults();
}
return false;
}
private boolean primitiveHasNoContent(final JPAEntityCollectionExtension entityCollection) {
final String name;
if (!entityCollection.hasResults())
return false;
name = Utility.determineStartNavigationPath(uriInfo.getUriResourceParts()).getProperty().getName();
final var property = entityCollection.getFirstResult().getProperty(name);
return (property != null && property.getValue() == null);
}
/**
* $expand is implemented as a recursively processing of all expands with a DB round trip per expand item.
* Alternatively also a <i>big</i> join could be created. This would lead to a transport of redundant data, but has
* only one round trip. As of now it has not been measured under which conditions which solution has the better
* performance, but a big join has also the following draw back:
* <ul>
* <li>In case a multiple $expands are requested maybe on multiple levels
* including filtering and ordering the query becomes very complex which reduces the maintainability and comes with
* the risk that some databases are not able to handles those.</li>
* <li>The number of returned columns becomes big, which may become a problem for some databases</li>
* <li>This hard to create a big join for <code>$level=*</code></li>
* <li>Server driven paging seems to be more complicated</li>
* </ul>
* and the goal is to implement a general solution, multiple round trips have been taken.
* <p>
* For a general overview see:
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398298"
* >OData Version 4.0 Part 1 - 11.2.4.2 System Query Option $expand</a>
* <p>
*
* For a detailed description of the URI syntax see:
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398162"
* >OData Version 4.0 Part 2 - 5.1.2 System Query Option $expand</a> boundary
* @param headers
* @param parentHops
* @param uriResourceInfo
* @param keyBoundary
* @param watchDog
* @return
* @throws ODataException
*/
private Map<JPAAssociationPath, JPAExpandResult> readExpandEntities(final Map<String, List<String>> headers,
final List<JPANavigationPropertyInfo> parentHops, final UriInfoResource uriResourceInfo,
final Optional<JPAKeyBoundary> keyBoundary, final JPAExpandWatchDog watchDog) throws ODataException {
try (var expandMeasurement = debugger.newMeasurement(this, "readExpandEntities")) {
final var factory = new JPAExpandQueryFactory(odata, requestContext, cb);
final Map<JPAAssociationPath, JPAExpandResult> allExpResults = new HashMap<>();
if (watchDog.getRemainingLevels() > 0) {
// x/a?$expand=b/c($expand=d,e/f)&$filter=...&$top=3&$orderBy=...
// x?$expand=*(levels=3)
// For performance reasons the expand query should only return results for the results of the higher-level
// query.
// The solution for restrictions like a given key or a given filter condition, as it can be propagated to a
// sub-query.
// For $top and $skip things are more difficult as the Subquery does not support LIMIT and OFFSET, this is
// done on the TypedQuery created out of the CriteriaQuery. In addition not all databases support LIMIT within a
// sub-query used within EXISTS.
// Solution: Forward the highest and lowest key from the root and create a "between" those.
final var itemInfoList = new JPAExpandItemInfoFactory(requestContext)
.buildExpandItemInfo(sd, uriResourceInfo, parentHops, keyBoundary, factory);
for (final JPAExpandItemInfo item : watchDog.filter(itemInfoList)) {
final var expandQuery = factory.createQuery(item, keyBoundary);
final var expandResult = expandQuery.execute();
if (expandResult.getNoResults() > 0)
// Only go to the next hop if the current one has a result
expandResult.putChildren(readExpandEntities(headers, item.getHops(), item.getUriInfo(), keyBoundary,
watchDog));
allExpResults.put(item.getExpandAssociation(), expandResult);
}
watchDog.levelProcessed();
}
// process collection attributes
final var collectionInfoList = new JPAExpandItemInfoFactory(requestContext)
.buildCollectionItemInfo(sd, uriResourceInfo, parentHops, requestContext.getGroupsProvider());
for (final JPACollectionItemInfo item : collectionInfoList) {
final var collectionQuery = new JPACollectionJoinQuery(odata, item,
new JPAODataInternalRequestContext(item.getUriInfo(), requestContext, headers), keyBoundary);
final JPAExpandResult expandResult = collectionQuery.execute();
allExpResults.put(item.getExpandAssociation(), expandResult);
}
return allExpResults;
}
}
private static Optional<JPAAnnotatable> determineTargetEntitySet(final JPAODataRequestContextAccess requestContext)
throws ODataException {
final var bindingTarget = Utility.determineBindingTarget(requestContext.getUriInfo()
.getUriResourceParts());
if (bindingTarget instanceof EdmEntitySet)
return requestContext.getEdmProvider().getServiceDocument().getEntitySet(bindingTarget.getName())
.map(JPAAnnotatable.class::cast);
return Optional.empty();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAHookFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAHookFactory.java | package com.sap.olingo.jpa.processor.core.processor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.EntityManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
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.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAQueryExtension;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
final class JPAHookFactory {
private static final Log LOGGER = LogFactory.getLog(JPAHookFactory.class);
private final Map<JPAAttribute, EdmTransientPropertyCalculator<?>> transientCalculatorCache;
private final Map<JPAEntityType, EdmQueryExtensionProvider> queryExtensionProviderCache;
private final JPAHttpHeaderMap header;
private final EntityManager em;
private final JPARequestParameterMap requestParameter;
JPAHookFactory(final EntityManager em, final JPAHttpHeaderMap header, final JPARequestParameterMap parameter) {
super();
this.transientCalculatorCache = new HashMap<>();
this.queryExtensionProviderCache = new HashMap<>();
this.em = em;
this.header = header;
this.requestParameter = parameter;
}
public Optional<EdmTransientPropertyCalculator<?>> getTransientPropertyCalculator(
@Nonnull final JPAAttribute transientProperty) throws ODataJPAProcessorException {
try {
if (transientProperty.isTransient()) {
if (!transientCalculatorCache.containsKey(transientProperty)) {
createCalculator(transientProperty);
}
return Optional.of(transientCalculatorCache.get(transientProperty));
}
} catch (ODataJPAModelException | InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return Optional.empty();
}
public Optional<EdmQueryExtensionProvider> getQueryExtensionProvider(
@Nonnull final JPAEntityType et) throws ODataJPAProcessorException {
if (!queryExtensionProviderCache.containsKey(et)) {
try {
queryExtensionProviderCache.put(et, et.getQueryExtension()
.map(this::createQueryExtensionProvider)
.orElse(null));
} catch (final Exception e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
return Optional.ofNullable(queryExtensionProviderCache.get(et));
}
private void createCalculator(final JPAAttribute transientProperty) throws ODataJPAModelException,
InstantiationException, IllegalAccessException, InvocationTargetException {
final Constructor<? extends EdmTransientPropertyCalculator<?>> c = transientProperty
.getCalculatorConstructor();
final Parameter[] parameters = c.getParameters();
final Object[] paramValues = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
final Parameter parameter = parameters[i];
if (parameter.getType().isAssignableFrom(EntityManager.class))
paramValues[i] = em;
if (parameter.getType().isAssignableFrom(JPAHttpHeaderMap.class))
paramValues[i] = header;
if (parameter.getType().isAssignableFrom(JPARequestParameterMap.class))
paramValues[i] = requestParameter;
}
final EdmTransientPropertyCalculator<?> calculator = c.newInstance(paramValues);
transientCalculatorCache.put(transientProperty, calculator);
}
private EdmQueryExtensionProvider createQueryExtensionProvider(
final JPAQueryExtension<EdmQueryExtensionProvider> queryExtension) {
final Constructor<?> c = queryExtension.getConstructor();
try {
final Parameter[] parameters = c.getParameters();
final Object[] paramValues = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
final Parameter parameter = parameters[i];
if (parameter.getType().isAssignableFrom(JPAHttpHeaderMap.class))
paramValues[i] = header;
if (parameter.getType().isAssignableFrom(JPARequestParameterMap.class))
paramValues[i] = requestParameter;
}
return (EdmQueryExtensionProvider) c.newInstance(paramValues);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.error("Cloud not create Query Extension: " + c.getDeclaringClass().getName(), e);
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAHttpHeaderHashMap.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAHttpHeaderHashMap.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
class JPAHttpHeaderHashMap extends HashMap<String, List<String>> implements JPAHttpHeaderMap {
private static final long serialVersionUID = 7678027573813050132L;
public JPAHttpHeaderHashMap(final Map<String, List<String>> map) {
super(map);
}
public JPAHttpHeaderHashMap() {
super();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPACountRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPACountRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceSingleton;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.query.JPAJoinCountQuery;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollection;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
/**
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398314">
* OData Version 4.0 Part 2 - 11.2.9 Requesting the Number of Items in a Collection</a>
*/
public final class JPACountRequestProcessor extends JPAAbstractGetRequestProcessor {
public JPACountRequestProcessor(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
}
@Override
public void retrieveData(final ODataRequest request, final ODataResponse response, final ContentType responseFormat)
throws ODataException {
final var uriResource = uriInfo.getUriResourceParts().get(0);
if (uriResource instanceof UriResourceEntitySet
|| uriResource instanceof UriResourceSingleton) {
final var result = countEntities();
createSuccessResponse(response, ContentType.TEXT_PLAIN, serializer.serialize(request, result), null);
} else {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_RESOURCE_TYPE,
HttpStatusCode.NOT_IMPLEMENTED, uriResource.getKind().toString());
}
}
protected final JPAEntityCollectionExtension countEntities()
throws ODataException {
JPAJoinCountQuery query = null;
try {
query = new JPAJoinCountQuery(odata, requestContext);
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.QUERY_PREPARATION_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
final var entityCollection = new JPAEntityCollection();
entityCollection.setCount(query.countResults().intValue());
return entityCollection;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestLink.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestLink.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.Map;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
public interface JPARequestLink {
/**
* Provides an instance of the target entity metadata
* @return
*/
public JPAEntityType getEntityType();
/**
* Map of related keys
* @return
* @throws ODataJPAProcessorException
*/
public Map<String, Object> getRelatedKeys() throws ODataJPAProcessorException;
public Map<String, Object> getValues() throws ODataJPAProcessorException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestParameterHashMap.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestParameterHashMap.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.HashMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
public class JPARequestParameterHashMap extends HashMap<String, Object> implements JPARequestParameterMap {
private static final long serialVersionUID = 1869470620805799005L;
public JPARequestParameterHashMap(final JPARequestParameterMap requestParameter) {
super(requestParameter);
}
public JPARequestParameterHashMap() {
super();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestLinkImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestLinkImpl.java | package com.sap.olingo.jpa.processor.core.processor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import 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.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
final class JPARequestLinkImpl implements JPARequestLink {
private final JPAAssociationPath path;
private final String bindingLink;
private final Map<String, Object> keys;
private final Map<String, Object> values;
private final JPAConversionHelper helper;
JPARequestLinkImpl(final JPAAssociationPath path, final String bindingLink, final JPAConversionHelper helper) {
super();
this.path = path;
this.bindingLink = bindingLink;
this.helper = helper;
this.keys = new HashMap<>();
this.values = new HashMap<>();
}
@Override
public JPAEntityType getEntityType() {
return (JPAEntityType) path.getTargetType();
}
@Override
public Map<String, Object> getRelatedKeys() throws ODataJPAProcessorException {
if (keys.size() == 0) try {
buildKeys();
} catch (final Exception e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.BAD_REQUEST);
}
return keys;
}
@Override
public Map<String, Object> getValues() throws ODataJPAProcessorException {
if (values.size() == 0) try {
buildKeys();
} catch (final Exception e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.BAD_REQUEST);
}
return values;
}
private void buildKeys() throws ODataJPAModelException, NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException, EdmPrimitiveTypeException {
final OData odata = OData.newInstance();
// TODO replace by Olingo OData Util
final String[] entityTypeAndKey = bindingLink.split("[\\(\\)]");
final String[] keyElements = entityTypeAndKey[1].split("[,=]");
if (keyElements.length > 1) {
buildCompoundKeys(odata, keyElements);
} else {
buildSimpleKeys(odata, keyElements);
}
}
private void buildSimpleKeys(final OData odata, final String[] keyElements) throws ODataJPAModelException,
NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException,
EdmPrimitiveTypeException {
// If an entity has only one key property, it is allowed to omit the property name
final List<JPAAttribute> targetKeys = ((JPAEntityType) path.getTargetType()).getKey();
final String attributeName = targetKeys.get(0).getInternalName();
final JPAOnConditionItem item = path.getJoinColumnsList().get(0);
if (item.getRightPath().getLeaf().getInternalName().equals(attributeName)) {
keys.put(item.getRightPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[0].trim(), item
.getRightPath()));
values.put(item.getLeftPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[0].trim(), item
.getLeftPath()));
return;
}
if (item.getLeftPath().getLeaf().getInternalName().equals(attributeName)) {
keys.put(item.getLeftPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[0].trim(), item
.getLeftPath()));
values.put(item.getRightPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[0].trim(), item
.getRightPath()));
}
}
private void buildCompoundKeys(final OData odata, final String[] keyElements) throws ODataJPAModelException,
NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException,
EdmPrimitiveTypeException {
for (int i = 0; i < keyElements.length; i += 2) {
for (final JPAOnConditionItem item : path.getJoinColumnsList()) {
if (item.getLeftPath().getLeaf().getExternalName().equals(keyElements[i].trim())) {
keys.put(item.getLeftPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[i + 1].trim(),
item.getLeftPath()));
values.put(item.getRightPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[i + 1]
.trim(), item.getRightPath()));
break;
}
if (item.getRightPath().getLeaf().getExternalName().equals(keyElements[i].trim())) {
keys.put(item.getRightPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[i + 1].trim(),
item.getRightPath()));
values.put(item.getLeftPath().getLeaf().getInternalName(), convertKeyValue(odata, keyElements[i + 1].trim(),
item.getLeftPath()));
}
}
}
}
private Object convertKeyValue(final OData odata, final String keyElementValue, final JPAPath path)
throws ODataJPAModelException, NoSuchMethodException, InstantiationException, IllegalAccessException,
InvocationTargetException, EdmPrimitiveTypeException {
final EdmPrimitiveType edmType = odata.createPrimitiveTypeInstance(path.getLeaf().getEdmType());
final Class<?> defaultType = edmType.getDefaultType();
final Constructor<?> c = defaultType.getConstructor(String.class);
final Object value = c.newInstance(edmType.fromUriLiteral(keyElementValue));
return helper.processAttributeConverter(value, path.getLeaf());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPACUDRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPACUDRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ATTRIBUTE_NOT_FOUND;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.BEFORE_IMAGE_MERGED;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ENTITY_TYPE_UNKNOWN;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.RETURN_MISSING_ENTITY;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.RETURN_NULL;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.WRONG_RETURN_TYPE;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import static org.apache.olingo.commons.api.http.HttpStatusCode.NO_CONTENT;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.Link;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.prefer.Preferences;
import org.apache.olingo.server.api.prefer.Preferences.Return;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceComplexProperty;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.UriResourceValue;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPATopLevelEntity;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory.JPAODataTransaction;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPASerializerException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPATransactionException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
import com.sap.olingo.jpa.processor.core.modify.JPACreateResultFactory;
import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult;
import com.sap.olingo.jpa.processor.core.query.EdmBindingTargetInfo;
import com.sap.olingo.jpa.processor.core.query.ExpressionUtility;
import com.sap.olingo.jpa.processor.core.query.Utility;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollection;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
public final class JPACUDRequestProcessor extends JPAAbstractRequestProcessor {
private static final String DEBUG_CREATE_ENTITY = "createEntity";
private static final String DEBUG_UPDATE_ENTITY = "updateEntity";
private final ServiceMetadata serviceMetadata;
private final JPAConversionHelper helper;
public JPACUDRequestProcessor(final OData odata, final ServiceMetadata serviceMetadata,
final JPAODataRequestContextAccess requestContext,
final JPAConversionHelper cudHelper) throws ODataException {
super(odata, requestContext);
this.serviceMetadata = serviceMetadata;
this.helper = cudHelper;
}
public void clearFields(final ODataRequest request, final ODataResponse response) throws ODataJPAProcessException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "clearFields")) {
final JPACUDRequestHandler handler = requestContext.getCUDRequestHandler();
final EdmBindingTargetInfo edmEntitySetInfo = Utility.determineBindingTargetAndKeys(uriInfo
.getUriResourceParts());
final JPARequestEntity requestEntity = createRequestEntity(edmEntitySetInfo, uriInfo.getUriResourceParts(),
request.getAllHeaders());
JPAODataTransaction ownTransaction = null;
final boolean foreignTransaction = requestContext.getTransactionFactory().hasActiveTransaction();
if (!foreignTransaction)
ownTransaction = requestContext.getTransactionFactory().createTransaction();
try (JPARuntimeMeasurement updateMeasurement = debugger.newMeasurement(this, DEBUG_UPDATE_ENTITY)) {
handler.updateEntity(requestEntity, em, determineHttpVerb(request, uriInfo.getUriResourceParts()));
if (!foreignTransaction)
handler.validateChanges(em);
} catch (final ODataJPAProcessException e) {
checkForRollback(ownTransaction, foreignTransaction);
throw e;
} catch (final Exception e) {
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
if (!foreignTransaction)
ownTransaction.commit();
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
}
public void createEntity(final ODataRequest request, final ODataResponse response, final ContentType requestFormat,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, DEBUG_CREATE_ENTITY)) {
final JPACUDRequestHandler handler = requestContext.getCUDRequestHandler();
final EdmBindingTargetInfo edmEntitySetInfo = Utility.determineModifyEntitySetAndKeys(uriInfo
.getUriResourceParts());
final Entity odataEntity = helper.convertInputStream(odata, request, requestFormat, uriInfo
.getUriResourceParts());
final JPARequestEntity requestEntity = createRequestEntity(edmEntitySetInfo, odataEntity, request
.getAllHeaders());
// Create entity
Object result = null;
JPAODataTransaction ownTransaction = null;
final boolean foreignTransaction = requestContext.getTransactionFactory().hasActiveTransaction();
if (!foreignTransaction)
ownTransaction = requestContext.getTransactionFactory().createTransaction();
try (JPARuntimeMeasurement createMeasurement = debugger.newMeasurement(this, DEBUG_CREATE_ENTITY)) {
result = handler.createEntity(requestEntity, em);
if (!foreignTransaction)
handler.validateChanges(em);
} catch (final ODataJPAProcessException e) {
checkForRollback(ownTransaction, foreignTransaction);
throw e;
} catch (final Exception e) {
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
if (result != null && result.getClass() != requestEntity.getEntityType().getTypeClass()
&& !(result instanceof Map<?, ?>)) {
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(WRONG_RETURN_TYPE, INTERNAL_SERVER_ERROR, result.getClass().toString(),
requestEntity.getEntityType().getTypeClass().toString());
}
if (!foreignTransaction)
ownTransaction.commit();
createCreateResponse(request, response, responseFormat, requestEntity, edmEntitySetInfo, result);
}
}
/*
* 4.4 Addressing References between Entities
* DELETE http://host/service/Categories(1)/Products/$ref?$id=../../Products(0)
* DELETE http://host/service/Products(0)/Category/$ref
*/
public void deleteEntity(final ODataRequest request, final ODataResponse response) throws ODataJPAProcessException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, "deleteEntity")) {
final JPACUDRequestHandler handler = requestContext.getCUDRequestHandler();
final JPAEntityType et;
final Map<String, Object> jpaKeyPredicates = new HashMap<>();
// 1. Retrieve the entity set which belongs to the requested entity
final List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
// Note: only in our example we can assume that the first segment is the EntitySet
final UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
final EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
Optional<JPATopLevelEntity> es = Optional.empty();
// 2. Convert Key from URL to JPA
try {
es = sd.getTopLevelEntity(edmEntitySet.getName());
et = sd.getEntity(edmEntitySet.getName());
if (et == null)
throw new ODataJPAProcessorException(ENTITY_TYPE_UNKNOWN, BAD_REQUEST, edmEntitySet.getName());
final List<UriParameter> uriKeyPredicates = uriResourceEntitySet.getKeyPredicates();
for (final UriParameter uriParam : uriKeyPredicates) {
final JPAAttribute attribute = getJPAPath(et, uriParam.getName()).getLeaf();
jpaKeyPredicates.put(attribute.getInternalName(), ExpressionUtility.convertValueOnAttribute(odata, attribute,
uriParam.getText(), true));
}
} catch (final ODataException e) {
throw new ODataJPAProcessorException(e, BAD_REQUEST);
}
final JPARequestEntity requestEntity = createRequestEntity(es, et, jpaKeyPredicates, request.getAllHeaders());
// 3. Perform Delete
JPAODataTransaction ownTransaction = null;
final boolean foreignTransaction = requestContext.getTransactionFactory().hasActiveTransaction();
if (!foreignTransaction)
ownTransaction = requestContext.getTransactionFactory().createTransaction();
try (JPARuntimeMeasurement deleteMeasurement = debugger.newMeasurement(this, "deleteEntity")) {
handler.deleteEntity(requestEntity, em);
if (!foreignTransaction)
handler.validateChanges(em);
} catch (final ODataJPAProcessException e) {
checkForRollback(ownTransaction, foreignTransaction);
throw e;
} catch (final Throwable e) { // NOSONAR
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
if (!foreignTransaction)
ownTransaction.commit();
// 4. configure the response object
response.setStatusCode(NO_CONTENT.getStatusCode());
}
}
public void updateEntity(final ODataRequest request, final ODataResponse response, final ContentType requestFormat,
final ContentType responseFormat) throws ODataJPAProcessException, ODataLibraryException {
try (JPARuntimeMeasurement measurement = debugger.newMeasurement(this, DEBUG_UPDATE_ENTITY)) {
final JPACUDRequestHandler handler = requestContext.getCUDRequestHandler();
final EdmBindingTargetInfo edmBindingTargetInfo = Utility.determineModifyEntitySetAndKeys(uriInfo
.getUriResourceParts());
final Entity odataEntity = helper.convertInputStream(odata, request, requestFormat, uriInfo
.getUriResourceParts());
// http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752300
// 11.4.3 Update an Entity
// ...
// The entity MUST NOT contain related entities as inline content. It MAY contain binding information for
// navigation properties. For single-valued navigation properties this replaces the relationship. For
// collection-valued navigation properties this adds to the relationship.
// TODO navigation properties this replaces the relationship
final JPARequestEntity requestEntity = createRequestEntity(edmBindingTargetInfo, odataEntity, request
.getAllHeaders());
// Update entity
JPAUpdateResult updateResult = null;
JPAODataTransaction ownTransaction = null;
final boolean foreignTransaction = requestContext.getTransactionFactory().hasActiveTransaction();
if (!foreignTransaction)
ownTransaction = requestContext.getTransactionFactory().createTransaction();
try {
// http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752300
// 11.4.3 Update an Entity
// Services SHOULD support PATCH as the preferred means of updating an entity. ... .Services MAY additionally
// support PUT, but should be aware of the potential for data-loss in round-tripping properties that the client
// may not know about in advance, such as open or added properties, or properties not specified in metadata.
// 11.4.4 Upsert an Entity
// To ensure that an update request is not treated as an insert, the client MAY specify an If-Match header in
// the
// update request. The service MUST NOT treat an update request containing an If-Match header as an insert.
// A PUT or PATCH request MUST NOT be treated as an update if an If-None-Match header is specified with a value
// of
// "*".
updateResult = handler.updateEntity(requestEntity, em, determineHttpVerb(request, uriInfo
.getUriResourceParts()));
if (!foreignTransaction)
handler.validateChanges(em);
} catch (final ODataJPAProcessException e) {
checkForRollback(ownTransaction, foreignTransaction);
throw e;
} catch (final Throwable e) {
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
if (updateResult == null) {
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(RETURN_NULL, INTERNAL_SERVER_ERROR);
}
if (updateResult.modifiedEntity() != null && !requestEntity.getEntityType().getTypeClass().isInstance(
updateResult.modifiedEntity())) {
checkForRollback(ownTransaction, foreignTransaction);
throw new ODataJPAProcessorException(WRONG_RETURN_TYPE, INTERNAL_SERVER_ERROR,
updateResult.modifiedEntity().getClass().toString(), requestEntity.getEntityType().getTypeClass()
.toString());
}
if (!foreignTransaction)
ownTransaction.commit();
if (updateResult.wasCreate()) {
createCreateResponse(request, response, responseFormat, requestEntity.getEntityType(),
(EdmEntitySet) edmBindingTargetInfo.getEdmBindingTarget(), updateResult.modifiedEntity()); // Singleton
} else {
createUpdateResponse(request, response, responseFormat, requestEntity, edmBindingTargetInfo, updateResult);
}
}
}
private void checkForRollback(final JPAODataTransaction ownTransaction, final boolean foreignTransaction)
throws ODataJPATransactionException {
if (!foreignTransaction)
ownTransaction.rollback();
}
private HttpMethod determineHttpVerb(final ODataRequest request, final List<UriResource> resourceParts) {
final HttpMethod originalMethod = request.getMethod();
final HttpMethod targetMethod;
final int noResourceParts = resourceParts.size();
if (originalMethod == HttpMethod.PUT && resourceParts.get(noResourceParts - 1) instanceof UriResourceProperty) {
targetMethod = HttpMethod.PATCH;
} else {
targetMethod = originalMethod;
}
return targetMethod;
}
final JPARequestEntity createRequestEntity(final EdmBindingTargetInfo edmBindingTargetInfo, final Entity odataEntity,
final Map<String, List<String>> headers) throws ODataJPAProcessorException {
try {
final JPAEntityType et = sd.getEntity(edmBindingTargetInfo.getName());
final Optional<JPATopLevelEntity> es = sd.getTopLevelEntity(edmBindingTargetInfo.getName());
if (et == null)
throw new ODataJPAProcessorException(ENTITY_TYPE_UNKNOWN, BAD_REQUEST, edmBindingTargetInfo.getName());
final Map<String, Object> keys = helper.convertUriKeys(odata, et, edmBindingTargetInfo.getKeyPredicates());
final JPARequestEntityImpl requestEntity = (JPARequestEntityImpl) createRequestEntity(es, et, odataEntity, keys,
headers, et.getAssociationPath(edmBindingTargetInfo.getNavigationPath()));
requestEntity.setBeforeImage(createBeforeImage(requestEntity, em));
return requestEntity;
} catch (final ODataException e) {
throw new ODataJPAProcessorException(e, BAD_REQUEST);
}
}
/**
* Converts the deserialized request into the internal (JPA) format, which shall be provided to the hook method
* @param edmEntitySet
* @param odataEntity
* @param headers
* @return
* @throws ODataJPAProcessorException
*/
final JPARequestEntity createRequestEntity(final Optional<JPATopLevelEntity> topLevelEntity, final JPAEntityType et,
final Entity odataEntity,
final Map<String, Object> keys, final Map<String, List<String>> headers,
final JPAAssociationPath jpaAssociationPath) throws ODataJPAProcessorException {
try {
if (jpaAssociationPath == null) {
final Map<String, Object> jpaAttributes = helper.convertProperties(odata, et, odataEntity.getProperties());
final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities = createInlineEntities(et, odataEntity,
headers);
final Map<JPAAssociationPath, List<JPARequestLink>> relationLinks = createRelationLinks(et, odataEntity);
return new JPARequestEntityImpl(topLevelEntity, et, jpaAttributes, relatedEntities, relationLinks, keys,
headers, requestContext);
} else {
// Handle requests like POST
// .../AdministrativeDivisions(DivisionCode='DE6',CodeID='NUTS1',CodePublisher='Eurostat')/Children
final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities = createInlineEntities(odataEntity,
jpaAssociationPath, headers);
return new JPARequestEntityImpl(topLevelEntity, et, Collections.emptyMap(), relatedEntities, Collections
.emptyMap(), keys,
headers, requestContext);
}
} catch (final ODataException e) {
throw new ODataJPAProcessorException(e, BAD_REQUEST);
}
}
/**
* Create an RequestEntity instance for delete requests
* @param et
* @param keys
* @param headers
* @return
*/
final JPARequestEntity createRequestEntity(final Optional<JPATopLevelEntity> es, final JPAEntityType et,
final Map<String, Object> keys, final Map<String, List<String>> headers) {
final Map<String, Object> jpaAttributes = new HashMap<>(0);
final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities = new HashMap<>(0);
final Map<JPAAssociationPath, List<JPARequestLink>> relationLinks = new HashMap<>(0);
return new JPARequestEntityImpl(es, et, jpaAttributes, relatedEntities, relationLinks, keys, headers,
requestContext);
}
private Entity convertEntity(final JPAEntityType et, final Object result, final Map<String, List<String>> headers)
throws ODataJPAProcessorException {
try {
final JPATupleChildConverter converter = new JPATupleChildConverter(sd, odata.createUriHelper(), serviceMetadata,
requestContext);
final JPACreateResultFactory factory = new JPACreateResultFactory(converter);//
return converter.getResult(factory.getJPACreateResult(et, result, headers), Collections.emptySet())
.get(ROOT_RESULT_KEY).getEntities().get(0);
} catch (ODataJPAModelException | ODataApplicationException e) {
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
}
private Map<String, Object> convertUriPath(final JPAEntityType et, final List<UriResource> resourcePaths)
throws ODataJPAModelException, ODataJPAProcessorException {
final Map<String, Object> jpaAttributes = new HashMap<>();
Map<String, Object> currentMap = jpaAttributes;
JPAStructuredType st = et;
int lastIndex;
if (resourcePaths.get(resourcePaths.size() - 1) instanceof UriResourceValue)
lastIndex = resourcePaths.size() - 1;
else
lastIndex = resourcePaths.size();
for (int i = 1; i < lastIndex; i++) {
final UriResourceProperty uriResourceProperty = (UriResourceProperty) resourcePaths.get(i);
final JPAPath path = getJPAPath(st, uriResourceProperty.getProperty().getName());
if (uriResourceProperty instanceof UriResourceComplexProperty && i < resourcePaths.size() - 1) {
final Map<String, Object> jpaEmbedded = new HashMap<>();
final String internalName = path.getPath().get(0).getInternalName();
currentMap.put(internalName, jpaEmbedded);
currentMap = jpaEmbedded;
st = st.getAttribute(internalName).orElseThrow(() -> new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND,
INTERNAL_SERVER_ERROR, internalName)).getStructuredType();
} else {
currentMap.put(path.getLeaf().getInternalName(), null);
}
}
return jpaAttributes;
}
@Nonnull
private JPAPath getJPAPath(final JPAStructuredType st, final String name)
throws ODataJPAProcessorException {
try {
final var jpaPath = st.getPath(name);
if (jpaPath != null)
return jpaPath;
else
throw new ODataJPAProcessorException(ATTRIBUTE_NOT_FOUND, INTERNAL_SERVER_ERROR, name);
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, BAD_REQUEST);
}
}
private Optional<Object> createBeforeImage(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessorException, ODataJPAInvocationTargetException {
if (!requestEntity.getKeys().isEmpty()) {
final Object key = requestEntity.getModifyUtil().createPrimaryKey(requestEntity.getEntityType(), requestEntity
.getKeys(), requestEntity.getEntityType());
final Optional<Object> beforeImage = Optional.ofNullable(em.find(requestEntity.getEntityType().getTypeClass(),
key));
if (beforeImage.isPresent())
em.detach(beforeImage.get());
return beforeImage;
}
return Optional.empty();
}
private void createCreateResponse(final ODataRequest request, final ODataResponse response,
final ContentType responseFormat, final JPAEntityType et, final EdmEntitySet edmEntitySet, final Object result)
throws SerializerException, ODataJPAProcessorException, ODataJPASerializerException {
// http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part1-protocol.html
// Create response:
// 8.3.2 Header Location
// The Location header MUST be returned in the response from a Create Entity or Create Media Entity request to
// specify the edit URL, or for read-only entities the read URL, of the created entity, and in responses returning
// 202 Accepted to specify the URL that the client can use to request the status of an asynchronous request.
//
// 8.3.3 Header OData-EntityId
// A response to a create or upsert operation that returns 204 No Content MUST include an OData-EntityId response
// header. The value of the header is the entity-id of the entity that was acted on by the request. The syntax of
// the OData-EntityId header is specified in [OData-ABNF].
//
// 8.2.8.7 Preference return=representation and return=minimal states:
// A preference of return=minimal requests that the service invoke the request but does not return content in the
// response. The service MAY apply this preference by returning 204 No Content in which case it MAY include a
// Preference-Applied response header containing the return=minimal preference.
// A preference of return=representation requests that the service invokes the request and returns the modified
// resource. The service MAY apply this preference by returning the representation of the successfully modified
// resource in the body of the response, formatted according to the rules specified for the requested format. In
// this case the service MAY include a Preference-Applied response header containing the return=representation
// preference.
//
// 11.4.1.5 Returning Results from Data Modification Requests
// Clients can request whether created or modified resources are returned from create, update, and upsert operations
// using the return preference header. In the absence of such a header, services SHOULD return the created or
// modified content unless the resource is a stream property value.
// When returning content other than for an update to a media entity stream, services MUST return the same content
// as a subsequent request to retrieve the same resource. For updating media entity streams, the content of a
// non-empty response body MUST be the updated media entity.
//
// 11.4.2 Create an Entity
// Upon successful completion, the response MUST contain a Location header that contains the edit URL or read URL of
// the created entity.
//
successStatusCode = HttpStatusCode.CREATED.getStatusCode();
final Preferences prefer = odata.createPreferences(request.getHeaders(HttpHeader.PREFER));
// TODO Stream properties
final String location = helper.convertKeyToLocal(odata, request, edmEntitySet, et, result);
if (prefer.getReturn() == Return.MINIMAL) {
createMinimalCreateResponse(response, location);
} else {
final Entity createdEntity = convertEntity(et, result, request.getAllHeaders());
final JPAEntityCollection entities = new JPAEntityCollection();
entities.getEntities().add(createdEntity);
createSuccessResponse(response, responseFormat, serializer.serialize(request, entities), entities);
response.setHeader(HttpHeader.LOCATION, location);
}
}
private void createCreateResponse(final ODataRequest request, final ODataResponse response,
final ContentType responseFormat, final JPARequestEntity requestEntity, final EdmBindingTargetInfo edmEntitySet,
final Object result) throws SerializerException, ODataJPAProcessorException, ODataJPASerializerException {
if (!requestEntity.getKeys().isEmpty()) {
// .../AdministrativeDivisions(DivisionCode='DE5',CodeID='NUTS1',CodePublisher='Eurostat')/Children
// As of now only one related entity can be created
try {
final JPAAssociationPath path = requestEntity.getEntityType().getAssociationPath(edmEntitySet
.getNavigationPath());
final JPARequestEntity linkedEntity = requestEntity.getRelatedEntities().get(path).get(0);
final Object linkedResult = getLinkedResult(result, path, requestEntity.getBeforeImage());
createCreateResponse(request, response, responseFormat, linkedEntity.getEntityType(),
(EdmEntitySet) edmEntitySet.getTargetEdmBindingTarget(), linkedResult);
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
} else {
createCreateResponse(request, response, responseFormat, requestEntity.getEntityType(),
(EdmEntitySet) edmEntitySet.getEdmBindingTarget(), result);
}
}
private Map<JPAAssociationPath, List<JPARequestEntity>> createInlineEntities(final Entity odataEntity,
final JPAAssociationPath path, final Map<String, List<String>> headers) throws ODataJPAProcessorException {
final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities = new HashMap<>(1);
final List<JPARequestEntity> inlineEntities = new ArrayList<>();
inlineEntities.add(createRequestEntity(Optional.empty(), (JPAEntityType) path.getTargetType(), odataEntity,
new HashMap<>(0), headers, null));
relatedEntities.put(path, inlineEntities);
return relatedEntities;
}
private Map<JPAAssociationPath, List<JPARequestEntity>> createInlineEntities(final JPAEntityType et,
final Entity odataEntity, final Map<String, List<String>> headers) throws ODataJPAModelException,
ODataJPAProcessorException {
final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities = new HashMap<>();
for (final JPAAssociationPath path : et.getAssociationPathList()) {
List<Property> stProperties = odataEntity.getProperties();
Property property = null;
for (final JPAElement pathItem : path.getPath()) {
if (pathItem == path.getLeaf()) { // We have reached the target and can process further
final Link navigationLink = property != null ? property.asComplex().getNavigationLink(pathItem
.getExternalName())
: odataEntity.getNavigationLink(pathItem.getExternalName());
createInlineEntities((JPAEntityType) path.getTargetType(), headers, relatedEntities, navigationLink, path);
}
property = findProperty(pathItem.getExternalName(), stProperties);
if (property == null) break;
if (property.isComplex()) {
stProperties = property.asComplex().getValue();
}
}
}
return relatedEntities;
}
private void createInlineEntities(final JPAEntityType st, final Map<String, List<String>> headers,
final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities, final Link navigationLink,
final JPAAssociationPath path) throws ODataJPAProcessorException {
if (navigationLink == null) return;
final List<JPARequestEntity> inlineEntities = new ArrayList<>();
if (path.getLeaf().isCollection()) {
for (final Entity e : navigationLink.getInlineEntitySet().getEntities()) {
inlineEntities.add(createRequestEntity(Optional.empty(), st, e, new HashMap<>(0), headers, null));
}
relatedEntities.put(path, inlineEntities);
} else {
inlineEntities.add(createRequestEntity(Optional.empty(), st, navigationLink.getInlineEntity(), new HashMap<>(0),
headers, null));
relatedEntities.put(path, inlineEntities);
}
}
private void createMinimalCreateResponse(final ODataResponse response, final String location) {
response.setStatusCode(NO_CONTENT.getStatusCode());
response.setHeader(HttpHeader.PREFERENCE_APPLIED, "return=minimal");
response.setHeader(HttpHeader.LOCATION, location);
response.setHeader(HttpHeader.ODATA_ENTITY_ID, location);
}
private Map<JPAAssociationPath, List<JPARequestLink>> createRelationLinks(final JPAEntityType et,
final Entity odataEntity)
throws ODataJPAModelException {
final Map<JPAAssociationPath, List<JPARequestLink>> relationLinks =
new HashMap<>();
for (final Link binding : odataEntity.getNavigationBindings()) {
final List<JPARequestLink> bindingLinks = new ArrayList<>();
final JPAAssociationPath path = et.getAssociationPath(binding.getTitle());
if (path.getLeaf().isCollection()) {
for (final String bindingLink : binding.getBindingLinks()) {
final JPARequestLink requestLink = new JPARequestLinkImpl(path, bindingLink, helper);
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | true |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPARequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
public interface JPARequestProcessor {
public <K extends Comparable<K>> void retrieveData(ODataRequest request, ODataResponse response,
ContentType responseFormat) throws ODataException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPACoreDebugger.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPACoreDebugger.java | package com.sap.olingo.jpa.processor.core.processor;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.server.api.debug.RuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
class JPACoreDebugger implements JPAServiceDebugger {
private final List<RuntimeMeasurement> runtimeInformation = new ArrayList<>();
private final boolean isDebugMode;
private final MemoryReader memoryReader;
JPACoreDebugger(final boolean isDebugMode) {
this.isDebugMode = isDebugMode;
this.memoryReader = new MemoryReader();
}
@Override
public void debug(final Object instance, final String log) {
final Long threadID = Thread.currentThread().getId();
LogFactory.getLog(instance.getClass().getCanonicalName())
.debug(String.format("thread: %d, logger: %s, info %s", threadID, this, log));
}
@Override
public void debug(final Object instance, final String pattern, final Object... arguments) {
final Log logger = LogFactory.getLog(instance.getClass().getCanonicalName());
if (logger.isDebugEnabled()) {
logger.debug(composeLog(pattern, arguments));
}
}
@Override
public List<RuntimeMeasurement> getRuntimeInformation() {
if (isDebugMode)
return runtimeInformation;
return Collections.emptyList();
}
@Override
public JPARuntimeMeasurement newMeasurement(final Object instance, final String methodName) {
final Measurement m = new Measurement(instance, methodName, memoryReader);
if (isDebugMode)
runtimeInformation.add(m);
return m;
}
@Override
public void trace(final Object instance, final String pattern, final Object... arguments) {
final Log logger = LogFactory.getLog(instance.getClass().getCanonicalName());
if (logger.isTraceEnabled()) {
logger.trace(composeLog(pattern, arguments));
}
}
public boolean hasMemoryInformation() {
return memoryReader.memoryConsumptionAvailable;
}
private Object[] composeArguments(final Long threadID, final Object... arguments) {
final Object[] allArgs = new Object[arguments.length + 1];
System.arraycopy(arguments, 0, allArgs, 1, arguments.length);
allArgs[0] = threadID;
return allArgs;
}
private String composeLog(final String pattern, final Object... arguments) {
final Long threadID = Thread.currentThread().getId();
final StringBuilder log = new StringBuilder().append("thread: %d, ").append(pattern);
return String.format(log.toString(), composeArguments(threadID, arguments));
}
private static class Measurement extends RuntimeMeasurement implements JPARuntimeMeasurement {
private final MemoryReader memoryReader;
private boolean closed;
private long usedMemory;
private long memoryStart;
public Measurement(final Object instance, final String methodName, final MemoryReader memoryReader) {
this.setTimeStarted(System.nanoTime());
this.setClassName(instance.getClass().getCanonicalName());
this.setMethodName(methodName);
this.memoryReader = memoryReader;
this.closed = false;
this.usedMemory = memoryReader.getCurrentThreadMemoryConsumption() / 1000;
this.memoryStart = getUsedMemory();
}
@Override
public void close() {
this.setTimeStopped(System.nanoTime());
this.closed = true;
final long threadID = Thread.currentThread().getId();
final long runtime = (this.getTimeStopped() - this.getTimeStarted()) / 1000;
final Long memory = memoryReader.getCurrentThreadMemoryConsumption() / 1000;
final long consumedMemory = (getUsedMemory() - memoryStart) / 1000;
usedMemory = memory - usedMemory;
LogFactory.getLog(this.getClassName())
.debug(String.format(
"thread: %d, method: %s, runtime [µs]: %d; over all memory [kb]: %d; additional memory [kb]: %d, %d",
threadID,
this.getMethodName(),
runtime,
memory,
usedMemory,
consumedMemory));
}
@Override
public long getMemoryConsumption() {
assert closed;
return usedMemory;
}
private long getUsedMemory() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
}
private static class MemoryReader {
private boolean memoryConsumptionAvailable = true;
public MemoryReader() {
super();
}
long getCurrentThreadMemoryConsumption() {
if (!memoryConsumptionAvailable) {
return 0L;
}
try {
return getMemoryConsumption();
} catch (final Exception e) {
memoryConsumptionAvailable = false;
}
return 0L;
}
private long getMemoryConsumption() {
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
if (threadMXBean instanceof final com.sun.management.ThreadMXBean sunMXBean) {
return sunMXBean.getCurrentThreadAllocatedBytes();
}
return 0L;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAInstanceCreator.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAInstanceCreator.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriParameter;
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.core.exception.ODataJPAFilterException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper;
/**
* Reflection API does not provide parameter names of the constructor => No name matching possible, so in case multiple
* keys have the same type can not be distinguished. Therefore priority is follows:
* follows:
* <ol>
* <li>Constructor with one parameter taking an instance of the IdClass if used</li>
* <li>Constructor with one parameter in case the entity has a single key and type is matching</li> *
* <li>Constructor without parameter and using setter to fill the key</li>
* </ol>
* Id Class Constructor without parameter and using setter to fill the key;
* @author Oliver Grande
* @since 1.10.0
* 08.09.2022
* @param <E> JPA Entity
*/
class JPAInstanceCreator<E extends JPAEntityType> {
private static final Log LOGGER = LogFactory.getLog(JPAInstanceCreator.class);
private final JPAConversionHelper helper;
private final JPAModifyUtil util;
private final E type;
private final OData odata;
private final Class<?> entityClass;
JPAInstanceCreator(final OData odata, final E type) {
super();
this.type = type;
this.odata = odata;
// Take the constructor of the original binding parameter, as Olingo may have selected an action having a super
// type has binding parameter and the corresponding Java class is abstract.
this.entityClass = type.getTypeClass();
this.helper = new JPAConversionHelper();
this.util = new JPAModifyUtil();
}
/**
* Preference:
* <p>
* - Constructor taking an instance of the idClass<br>
* - Constructor taking the key attributes<br>
* - Constructor without parameter<br>
* @param <T>
* @return
* @throws ODataJPAProcessorException
*/
@SuppressWarnings("unchecked")
<T> Optional<Constructor<T>> determinePreferredConstructor() throws ODataJPAProcessorException {
try {
Constructor<T> result = null;
final Constructor<T>[] constructors = (Constructor<T>[]) entityClass.getConstructors();
for (final Constructor<T> c : constructors) {
if (preferedCandidate(result, c))
result = c;
}
return Optional.ofNullable(result);
} catch (final SecurityException | ODataJPAModelException e) {
LOGGER.error("Error while determine constructor for binding parameter");
throw new ODataJPAProcessorException(e, INTERNAL_SERVER_ERROR);
}
}
Optional<Object> createInstance(final List<UriParameter> keyPredicates) throws ODataJPAProcessorException {
final Optional<Constructor<Object>> c = determinePreferredConstructor();
try {
if (c.isPresent()) {
final Map<String, Object> jpaAttributes = helper.convertUriKeys(odata, type, keyPredicates);
if (c.get().getParameterCount() == 0) {
final Object param = c.get().newInstance();
util.setAttributesDeep(jpaAttributes, param, type);
return Optional.of(param);
} else if (type.hasCompoundKey()) {
final Constructor<?> keyConstructor = type.getKeyType().getConstructor();
final Object key = keyConstructor.newInstance();
if (hasSetterForKeys(type.getKeyType())) {
util.setAttributesDeep(jpaAttributes, key, type);
return Optional.of(c.get().newInstance(key));
}
} else {
return Optional.of(c.get().newInstance(jpaAttributes.values().toArray()));
}
} else {
LOGGER.warn("No constructor found taking the key for: " + entityClass.getName());
}
} catch (ODataJPAFilterException | ODataJPAProcessorException | ODataJPAInvocationTargetException
| ODataJPAModelException | InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return Optional.empty();
}
private <T> boolean preferedCandidate(final Constructor<T> current, final Constructor<T> candidate)
throws ODataJPAModelException {
if (type.hasCompoundKey()) {
final Class<?> idClass = type.getKeyType();
if (candidate.getParameterTypes().length == 1 && candidate.getParameterTypes()[0] == idClass)
return true;
} else if (candidate.getParameterCount() == 1
&& candidate.getParameterTypes()[0].equals(type.getKeyType())) {
return true;
}
if (candidate.getParameterCount() == 0
&& !(current != null && current.getParameterCount() == 1 && type.hasCompoundKey())) {
return hasSetterForKeys(type.getTypeClass());
}
return false;
}
private boolean hasSetterForKeys(final Class<?> typeClass) throws ODataJPAModelException {
return util.buildSetterList(typeClass, type.getKey()).values().stream().noneMatch(Objects::isNull);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPADebugSupportWrapper.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPADebugSupportWrapper.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.LinkedList;
import java.util.List;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.debug.DebugInformation;
import org.apache.olingo.server.api.debug.DebugSupport;
import org.apache.olingo.server.api.debug.RuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger;
public class JPADebugSupportWrapper implements DebugSupport {
private final DebugSupport debugSupport;
private final List<JPAServiceDebugger> debuggers;
public JPADebugSupportWrapper(final DebugSupport debugSupport) {
super();
this.debugSupport = debugSupport;
this.debuggers = new LinkedList<>();
}
/*
* (non-Javadoc)
*
* @see org.apache.olingo.server.api.debug.DebugSupport#createDebugResponse(java.lang.String,
* org.apache.olingo.server.api.debug.DebugInformation)
*/
@Override
public ODataResponse createDebugResponse(final String debugFormat, final DebugInformation debugInfo) {
joinRuntimeInfo(debugInfo);
return debugSupport.createDebugResponse(debugFormat, debugInfo);
}
/*
* (non-Javadoc)
*
* @see org.apache.olingo.server.api.debug.DebugSupport#init(org.apache.olingo.server.api.OData)
*/
@Override
public void init(final OData odata) {
debugSupport.init(odata);
}
/*
* (non-Javadoc)
*
* @see org.apache.olingo.server.api.debug.DebugSupport#isUserAuthorized()
*/
@Override
public boolean isUserAuthorized() {
return debugSupport.isUserAuthorized();
}
synchronized void addDebugger(final JPAServiceDebugger debugger) {
this.debuggers.add(debugger);
}
private void joinRuntimeInfo(final DebugInformation debugInfo) {
// Olingo create a tree for runtime measurement in DebugTabRuntime.add(final RuntimeMeasurement
// runtimeMeasurement). The current algorithm (V4.3.0) not working well for batch requests if the own runtime info
// is just appended (addAll), so insert sorted.
// Additional remark: In case parts run in parallel the start time based ordering will fail completely ;-)
final List<RuntimeMeasurement> olingoInfo = debugInfo.getRuntimeInformation();
int startIndex = 0;
for (final JPAServiceDebugger debugger : debuggers) {
for (final RuntimeMeasurement m : debugger.getRuntimeInformation()) {
for (; startIndex < olingoInfo.size(); startIndex++) {
if (olingoInfo.get(startIndex).getTimeStarted() > m.getTimeStarted()) {
break;
}
}
olingoInfo.add(startIndex, m);
startIndex += 1;
}
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAOperationRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAOperationRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.olingo.commons.api.data.Annotatable;
import org.apache.olingo.commons.api.data.ComplexValue;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmComplexType;
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.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriHelper;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaOperation;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperation;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
import com.sap.olingo.jpa.processor.core.converter.JPAComplexResultConverter;
import com.sap.olingo.jpa.processor.core.converter.JPAEntityResultConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPASerializerException;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollection;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer;
abstract class JPAOperationRequestProcessor extends JPAAbstractRequestProcessor {
private static final String RESULT = "Result";
JPAOperationRequestProcessor(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
}
protected Annotatable convertResult(final Object result, final EdmType returnType,
final JPAOperation jpaOperation) throws ODataApplicationException {
switch (returnType.getKind()) {
case PRIMITIVE:
if (jpaOperation.getResultParameter().isCollection()) {
final List<Object> response = new ArrayList<>();
response.addAll((Collection<?>) result);
return new Property(null, RESULT, ValueType.COLLECTION_PRIMITIVE, response);
} else if (result == null) {
return null;
}
return new Property(null, RESULT, ValueType.PRIMITIVE, result);
case ENTITY:
return (Annotatable) createEntityCollection((EdmEntityType) returnType, result, odata.createUriHelper(),
jpaOperation);
case COMPLEX:
if (jpaOperation.getResultParameter().isCollection()) {
return new Property(null, RESULT, ValueType.COLLECTION_COMPLEX, createComplexCollection(
(EdmComplexType) returnType, result));
} else if (result == null) {
return null;
}
return new Property(null, RESULT, ValueType.COMPLEX, createComplexValue((EdmComplexType) returnType,
result));
default:
break;
}
return null;
}
private List<ComplexValue> createComplexCollection(final EdmComplexType returnType, final Object result)
throws ODataApplicationException {
final List<Object> jpaQueryResult = new ArrayList<>();
jpaQueryResult.addAll((Collection<?>) result);
try {
return new JPAComplexResultConverter(sd, jpaQueryResult, returnType).getResult();
} catch (SerializerException | URISyntaxException e) {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.QUERY_RESULT_CONV_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
private ComplexValue createComplexValue(final EdmComplexType returnType, final Object result)
throws ODataApplicationException {
final List<Object> jpaQueryResult = new ArrayList<>();
jpaQueryResult.add(result);
try {
final List<ComplexValue> valueList = new JPAComplexResultConverter(sd, jpaQueryResult, returnType).getResult();
return valueList.get(0);
} catch (SerializerException | URISyntaxException e) {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.QUERY_RESULT_CONV_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private JPAEntityCollectionExtension createEntityCollection(final EdmEntityType returnType, final Object result,
final UriHelper createUriHelper, final JPAOperation jpaOperation)
throws ODataApplicationException {
final List resultList = new ArrayList();
if (jpaOperation.getResultParameter().isCollection())
resultList.addAll((Collection<?>) result);
else if (result == null)
return null;
else
resultList.add(result);
try {
return new JPAEntityResultConverter(createUriHelper, sd, resultList, returnType, requestContext.getEtagHelper())
.getResult();
} catch (SerializerException | ODataJPAModelException | URISyntaxException e) {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.QUERY_RESULT_CONV_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
protected void serializeResult(final EdmType returnType, final ODataResponse response,
final ContentType responseFormat, final Annotatable result, final ODataRequest request)
throws ODataJPASerializerException, SerializerException {
if (result != null
&& !(result instanceof final JPAEntityCollectionExtension collection
&& collection.getEntities().isEmpty())) {
final JPAEntityCollectionExtension collection = result instanceof final JPAEntityCollectionExtension // NOSONAR
j
? j
: new JPAEntityCollection();
final SerializerResult serializerResult = ((JPAOperationSerializer) serializer).serialize(result, returnType,
request);
createSuccessResponse(response, responseFormat, serializerResult, collection);
} else {
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
}
protected Object createInstance(final JPAJavaOperation jpaOperation, final Object... parameters)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
final Constructor<?> constructor = jpaOperation.getConstructor();
final Object[] paramValues = new Object[constructor.getParameters().length];
int i = 0;
for (final Parameter p : constructor.getParameters()) {
for (final Object o : parameters) {
if (p.getType().isAssignableFrom(o.getClass())) {
paramValues[i] = o;
break;
}
}
i++;
}
return constructor.newInstance(paramValues);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAExpandWatchDog.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAExpandWatchDog.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.EXPAND_EXCEEDS_MAX_LEVEL;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.EXPAND_NON_SUPPORTED_AT_ALL;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.EXPAND_NON_SUPPORTED_EXPAND;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.queryoption.ExpandItem;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.helper.AbstractWatchDog;
import com.sap.olingo.jpa.processor.core.query.JPAExpandItemInfo;
/**
* In case an annotatable artifact has been annotated with Capabilities#ExpandRestrictions, it is checked that requested
* <a href = "https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#_Toc31361039">
* $expand</a> fulfill the restrictions. See: <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L524"><i>ExpandRestrictions</i></a>
* <p>
* @author Oliver Grande
* @since 1.1.1
* 22.03.2023
*/
class JPAExpandWatchDog extends AbstractWatchDog {
static final String MAX_LEVELS = "MaxLevels";
static final String NON_EXPANDABLE_PROPERTIES = "NonExpandableProperties";
static final String EXPANDABLE = "Expandable";
static final String VOCABULARY_ALIAS = "Capabilities";
static final String TERM = "ExpandRestrictions";
private final String externalName;
private final Optional<CsdlAnnotation> annotation;
private final boolean isExpandable;
private int remainingLevels;
private final List<String> nonExpandableProperties;
private final int maxLevels;
JPAExpandWatchDog(final Optional<JPAAnnotatable> annotatable) throws ODataJPAProcessException {
super();
Map<String, CsdlExpression> properties = Collections.emptyMap();
if (annotatable.isPresent()) {
try {
externalName = annotatable.get().getExternalName();
annotation = Optional.ofNullable(annotatable.get().getAnnotation(VOCABULARY_ALIAS, TERM));
if (annotation.isPresent()) {
properties = getAnnotationProperties(annotation);
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
} else {
annotation = Optional.empty();
externalName = "";
}
maxLevels = remainingLevels = initializeRemainingLevels(properties);
isExpandable = determineExpandable(properties);
nonExpandableProperties = determineNonExpandable(properties);
}
boolean isExpandable() {
return isExpandable;
}
int getRemainingLevels() {
return remainingLevels;
}
List<String> getNonExpandableProperties() {
return nonExpandableProperties;
}
/**
* Pre check of an expand request. It is check, if the requested expand operation violates a given ExpandRestrictions
* annotation. In case the expand operation contains a star on the first level the check is skipped. In case it
* contains a level=max, the navigation is ignored for the max level check.
* @param expandOption
* @param queryPath
* @throws ODataJPAProcessorException
*/
void watch(final ExpandOption expandOption, final List<UriResource> queryPath)
throws ODataJPAProcessorException {
if (expandOption != null && !isStarOnly(expandOption)) {
watchExpandable(expandOption);
watchExpandLevel(expandOption);
watchExpandPath(expandOption, queryPath);
}
}
List<JPAExpandItemInfo> filter(final List<JPAExpandItemInfo> itemInfoList) {
remainingLevels--;
return itemInfoList.stream()
.filter(info -> !nonExpandableProperties.contains(info.getExpandAssociation().getAlias()))
.toList();
}
private void watchExpandLevel(@Nonnull final ExpandOption expandOption) throws ODataJPAProcessorException {
for (final ExpandItem item : expandOption.getExpandItems()) {
final LevelsExpandOption levelOption = item.getLevelsOption();
if (levelOption != null && levelOption.getValue() > maxLevels)
throw new ODataJPAProcessorException(EXPAND_EXCEEDS_MAX_LEVEL, HttpStatusCode.BAD_REQUEST, externalName);
}
}
private void watchExpandPath(@Nonnull final ExpandOption expandOption, final List<UriResource> queryPath)
throws ODataJPAProcessorException {
int noLevels = 0;
for (final ExpandItem item : expandOption.getExpandItems()) {
final UriInfoResource expandPath = item.getResourcePath();
final String expand = buildExpandPath(queryPath, expandPath);
if (nonExpandableProperties.contains(expand))
throw new ODataJPAProcessorException(EXPAND_NON_SUPPORTED_EXPAND, HttpStatusCode.BAD_REQUEST,
expand, externalName);
final int nextDepth = determineDepth(item) + 1;
if (nextDepth > noLevels)
noLevels = nextDepth;
}
if (noLevels + 1 > maxLevels)
throw new ODataJPAProcessorException(EXPAND_EXCEEDS_MAX_LEVEL, HttpStatusCode.BAD_REQUEST, externalName);
}
private void watchExpandable(@Nonnull final ExpandOption expandOption) throws ODataJPAProcessorException {
if (!isExpandable && expandOption.getExpandItems() != null
&& !expandOption.getExpandItems().isEmpty())
throw new ODataJPAProcessorException(EXPAND_NON_SUPPORTED_AT_ALL, HttpStatusCode.BAD_REQUEST,
externalName);
}
private int determineDepth(final ExpandItem item) {
if (item.getExpandOption() != null
&& item.getExpandOption().getExpandItems() != null
&& !item.getExpandOption().getExpandItems().isEmpty()) {
int subDepth = 0;
for (final ExpandItem nextItem : item.getExpandOption().getExpandItems()) {
final int nextDepth = determineDepth(nextItem);
if (nextDepth > subDepth)
subDepth = nextDepth;
}
return subDepth + 1;
}
return 0;
}
private boolean isStarOnly(final ExpandOption expandOption) {
return expandOption.getExpandItems().stream()
.allMatch(ExpandItem::isStar);
}
private String buildExpandPath(final List<UriResource> queryPath, final UriInfoResource expandPath) {
return Arrays.asList(queryPath.subList(1, queryPath.size()), expandPath.getUriResourceParts())
.stream()
.flatMap(List::stream)
.map(UriResource::getSegmentValue)
.collect(Collectors.joining(JPAPath.PATH_SEPARATOR));
}
private List<String> determineNonExpandable(final Map<String, CsdlExpression> properties) {
return getNavigationPathItems(properties, NON_EXPANDABLE_PROPERTIES);
}
private boolean determineExpandable(final Map<String, CsdlExpression> properties) {
return determineConstantExpression(properties, EXPANDABLE)
.map(Boolean::valueOf)
.orElse(true);
}
private int initializeRemainingLevels(final Map<String, CsdlExpression> properties) {
// CsdlConstantExpression; -1 = no restriction
return determineConstantExpression(properties, MAX_LEVELS)
.map(Integer::valueOf)
.map(i -> i < 0 ? Integer.MAX_VALUE : i)
.orElse(Integer.MAX_VALUE);
}
public void levelProcessed() {
remainingLevels++;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAAbstractGetRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAAbstractGetRequestProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess;
abstract class JPAAbstractGetRequestProcessor extends JPAAbstractRequestProcessor implements JPARequestProcessor {
JPAAbstractGetRequestProcessor(final OData odata, final JPAODataRequestContextAccess requestContext)
throws ODataException {
super(odata, requestContext);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAJavaFunctionProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAJavaFunctionProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys.ENUMERATION_UNKNOWN;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
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.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEnumerationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAJavaOperation;
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.exception.ODataJPADBAdaptorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
public class JPAJavaFunctionProcessor {
private final UriResourceFunction uriResourceFunction;
private final JPAJavaFunction jpaFunction;
private final Object[] parameters;
private final JPAServiceDocument sd;
public JPAJavaFunctionProcessor(final JPAServiceDocument sd, final UriResourceFunction uriResourceFunction,
final JPAJavaFunction jpaFunction, final Object... parameter) {
this.uriResourceFunction = uriResourceFunction;
this.jpaFunction = jpaFunction;
this.parameters = parameter;
this.sd = sd;
}
public Object process() throws ODataApplicationException {
try {
final Object instance = createInstance(parameters, jpaFunction);
final List<Object> parameter = fillParameter(uriResourceFunction, jpaFunction);
return jpaFunction.getMethod().invoke(instance, parameter.toArray());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
} catch (final InvocationTargetException e) {
if (e.getCause() instanceof final ODataApplicationException cause) {
throw cause;
} else {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
private Object createInstance(final Object[] parameters, final JPAJavaOperation jpaOperation)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
final Constructor<?> c = jpaOperation.getConstructor();
final Object[] paramValues = new Object[c.getParameters().length];
int i = 0;
for (final Parameter p : c.getParameters()) {
for (final Object o : parameters) {
if (p.getType().isAssignableFrom(o.getClass())) {
paramValues[i] = o;
break;
}
}
i++;
}
return c.newInstance(paramValues);
}
private List<Object> fillParameter(final UriResourceFunction uriResourceFunction, final JPAJavaOperation jpaOperation)
throws ODataJPAModelException, ODataApplicationException {
final Parameter[] methodParameter = jpaOperation.getMethod().getParameters();
final List<Object> parameter = new ArrayList<>();
for (final Parameter declaredParameter : methodParameter) {
for (final UriParameter providedParameter : uriResourceFunction.getParameters()) {
final JPAParameter jpaParameter = jpaOperation.getParameter(declaredParameter);
if (jpaParameter.getName().equals(providedParameter.getName())) {
final String value = providedParameter.getText();
if (value != null)
parameter.add(getValue(uriResourceFunction.getFunction(), jpaParameter, value));
else
parameter.add(null);
break;
}
}
}
return parameter;
}
private Object getValue(final EdmFunction edmFunction, final JPAParameter parameter, final String uriValue)
throws ODataApplicationException {
final String value = uriValue.replace("'", "");
final EdmParameter edmParam = edmFunction.getParameter(parameter.getName());
try {
switch (edmParam.getType().getKind()) {
case PRIMITIVE:
return ((EdmPrimitiveType) edmParam.getType()).valueOfString(value, false, edmParam.getMaxLength(),
edmParam.getPrecision(), edmParam.getScale(), true, parameter.getType());
case ENUM:
final JPAEnumerationAttribute enumeration = sd.getEnumType(parameter.getTypeFQN()
.getFullQualifiedNameAsString());
if (enumeration == null)
throw new ODataJPAProcessorException(ENUMERATION_UNKNOWN, HttpStatusCode.BAD_REQUEST, parameter.getName());
return enumeration.enumOf(value);
default:
throw new ODataJPADBAdaptorException(ODataJPADBAdaptorException.MessageKeys.PARAMETER_CONVERSION_ERROR,
HttpStatusCode.NOT_IMPLEMENTED, uriValue, parameter.getName());
}
} catch (EdmPrimitiveTypeException | ODataJPAModelException e) {
// Unable to convert value %1$s of parameter %2$s
throw new ODataJPADBAdaptorException(ODataJPADBAdaptorException.MessageKeys.PARAMETER_CONVERSION_ERROR,
HttpStatusCode.NOT_IMPLEMENTED, e, uriValue, parameter.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/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPASerializerException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPASerializerException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
/*
* Copied from org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException
* See also org.apache.olingo.odata2.jpa.processor.core.exception.ODataJPAMessageServiceDefault
*/
public class ODataJPASerializerException extends ODataJPAProcessException { //NOSONAR
/**
*
*/
private static final long serialVersionUID = -7188499882306858747L;
public enum MessageKeys implements ODataJPAMessageKey {
RESULT_NOT_FOUND,
NOT_SUPPORTED_RESOURCE_TYPE;
@Override
public String getKey() {
return name();
}
}
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPASerializerException(final Throwable e, final HttpStatusCode statusCode) {
super(e, statusCode);
}
public ODataJPASerializerException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String... params) {
super(messageKey.getKey(), statusCode, cause, params);
}
public ODataJPASerializerException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public ODataJPASerializerException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final String... params) {
super(messageKey.getKey(), statusCode, params);
}
public ODataJPASerializerException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) {
super(messageKey.getKey(), statusCode, e);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAKeyPairException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAKeyPairException.java | package com.sap.olingo.jpa.processor.core.exception;
import static org.apache.olingo.commons.api.http.HttpStatusCode.INTERNAL_SERVER_ERROR;
public class ODataJPAKeyPairException extends ODataJPAProcessException {
private static final long serialVersionUID = 6006099025067551818L;
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
private static final String MESSAGE_KEY = "KEY_PAIR_CONVERSION_ERROR";
public ODataJPAKeyPairException(final Throwable cause, final String... params) {
super(MESSAGE_KEY, INTERNAL_SERVER_ERROR, cause, params);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAUtilException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAUtilException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
/*
* Copied from org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException
* See also org.apache.olingo.odata2.jpa.processor.core.exception.ODataJPAMessageServiceDefault
*/
public class ODataJPAUtilException extends ODataJPAProcessException {
/**
*
*/
private static final long serialVersionUID = -7188499882306858747L;
public enum MessageKeys implements ODataJPAMessageKey {
UNKNOWN_NAVI_PROPERTY,
UNKNOWN_ENTITY_TYPE;
@Override
public String getKey() {
return name();
}
}
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPAUtilException(final Throwable e, final HttpStatusCode statusCode) {
super(e, statusCode);
}
public ODataJPAUtilException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String... params) {
super(messageKey.getKey(), statusCode, cause, params);
}
public ODataJPAUtilException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public ODataJPAUtilException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final String... params) {
super(messageKey.getKey(), statusCode, params);
}
public ODataJPAUtilException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) {
super(messageKey.getKey(), statusCode, e);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAProcessException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAProcessException.java | package com.sap.olingo.jpa.processor.core.exception;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageBufferRead;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageTextBuffer;
public abstract class ODataJPAProcessException extends ODataApplicationException {
/**
*
*/
private static final long serialVersionUID = -3178033271311091314L;
private static final String UNKNOWN_MESSAGE = "No message text found";
protected final String id;
protected final String[] parameter;
protected final String messageText;
protected ODataJPAProcessException(final String id, final HttpStatusCode statusCode) {
this(id, null, statusCode, new String[] {});
}
protected ODataJPAProcessException(final Throwable cause, final HttpStatusCode statusCode) {
this(null, null, statusCode, cause, new String[] {});
}
protected ODataJPAProcessException(final String id, final HttpStatusCode statusCode, final Throwable cause) {
this(id, null, statusCode, cause, new String[] {});
}
protected ODataJPAProcessException(final String id, final HttpStatusCode statusCode, final Throwable cause,
final String[] params) {
this(id, null, statusCode, cause, params);
}
protected ODataJPAProcessException(final String id, final HttpStatusCode statusCode, final String[] params) {
this(id, null, statusCode, params);
}
/**
*
* @param id
* @param messageText
* @param statusCode
* @param params
*/
protected ODataJPAProcessException(final String id, final String messageText, final HttpStatusCode statusCode,
final String[] params) {
this(id, messageText, statusCode, null, params);
}
/**
*
* @param id
* @param messageText
* @param statusCode
* @param cause
* @param params
*/
protected ODataJPAProcessException(final String id, final String messageText, final HttpStatusCode statusCode,
final Throwable cause, final String[] params) {
super("", statusCode.getStatusCode(), Locale.ENGLISH, cause);
this.id = id;
this.parameter = params;
this.messageText = messageText;
}
protected ODataJPAMessageTextBuffer getTextBundle() {
if (getBundleName() != null)
return new ODataJPAMessageTextBuffer(getBundleName(), getLocale());
else
return null;
}
@Override
public String getLocalizedMessage() {
return getMessage();
}
@Override
public String getMessage() {
try {
final ODataJPAMessageBufferRead messageBuffer = getTextBundle();
if (messageBuffer != null && id != null) {
final String message = messageBuffer.getText(this, id, parameter);
if (message != null) {
return message;
}
return messageText;
} else if (getCause() != null) {
return getCause().getLocalizedMessage();
} else if (messageText != null && !messageText.isEmpty()) {
return messageText;
} else {
return UNKNOWN_MESSAGE;
}
} catch (final MissingResourceException e) {
final Log logger = LogFactory.getLog(this.getClass());
logger.error("Message bundle not found: " + getBundleName(), e);
}
return UNKNOWN_MESSAGE;
}
public List<String> getParameter() {
return Arrays.asList(parameter);
}
public String getId() {
return id;
}
protected abstract String getBundleName();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAQueryException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAQueryException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
/*
* Copied from org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException
* See also org.apache.olingo.odata2.jpa.processor.core.exception.ODataJPAMessageServiceDefault
*/
public class ODataJPAQueryException extends ODataJPAProcessException { // NOSONAR
/**
*
*/
private static final long serialVersionUID = -7188499882306858747L;
public enum MessageKeys implements ODataJPAMessageKey {
QUERY_RESULT_CONV_ERROR,
QUERY_RESULT_ENTITY_SET_ERROR,
QUERY_RESULT_ENTITY_TYPE_ERROR,
QUERY_RESULT_NAVI_PROPERTY_ERROR,
QUERY_RESULT_KEY_PROPERTY_ERROR,
QUERY_RESULT_NAVI_PROPERTY_UNKNOWN,
QUERY_RESULT_ACCESS_NOT_FOUND,
QUERY_RESULT_EXPAND_ERROR,
QUERY_RESULT_CONV_MISSING_GETTER,
QUERY_PREPARATION_FILTER_ERROR,
QUERY_PREPARATION_ENTITY_UNKNOWN,
QUERY_PREPARATION_INVALID_VALUE,
QUERY_PREPARATION_INVALID_SELECTION_PATH,
QUERY_PREPARATION_INVALID_KEY_PAIR,
QUERY_PREPARATION_ERROR,
QUERY_PREPARATION_JOIN_NOT_DEFINED,
QUERY_PREPARATION_NOT_IMPLEMENTED,
QUERY_PREPARATION_NOT_ALLOWED_MEMBER,
QUERY_PREPARATION_ORDER_BY_TRANSIENT,
QUERY_PREPARATION_ORDER_BY_NOT_SUPPORTED,
QUERY_PREPARATION_JOIN_TABLE_TYPE_MISSING,
QUERY_PREPARATION_COLLECTION_PROPERTY_NOT_SUPPORTED,
QUERY_PREPARATION_NO_PAGE_FOUND,
QUERY_PREPARATION_UNSUPPORTED_EXPAND,
NOT_SUPPORTED_RESOURCE_TYPE,
MISSING_CLAIMS_PROVIDER,
MISSING_CLAIM,
WILDCARD_UPPER_NOT_SUPPORTED,
QUERY_CHECK_SORTING_NOT_SUPPORTED,
QUERY_CHECK_SORTING_NOT_SUPPORTED_FOR,
QUERY_CHECK_ASCENDING_REQUIRED_FOR,
QUERY_CHECK_DESCENDING_REQUIRED_FOR;
@Override
public String getKey() {
return name();
}
}
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPAQueryException(final Throwable e, final HttpStatusCode statusCode) {
super(e, statusCode);
}
public ODataJPAQueryException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String... params) {
super(messageKey.getKey(), statusCode, cause, params);
}
public ODataJPAQueryException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public ODataJPAQueryException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final String... params) {
super(messageKey.getKey(), statusCode, params);
}
public ODataJPAQueryException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) {
super(messageKey.getKey(), statusCode, e);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPADBAdaptorException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPADBAdaptorException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
/*
* Copied from org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException
* See also org.apache.olingo.odata2.jpa.processor.core.exception.ODataJPAMessageServiceDefault
*/
public class ODataJPADBAdaptorException extends ODataJPAProcessException {
/**
*
*/
private static final long serialVersionUID = -7188499882306858747L;
public enum MessageKeys implements ODataJPAMessageKey {
PARAMETER_MISSING,
NOT_SUPPORTED_SEARCH,
PARAMETER_CONVERSION_ERROR,
WRONG_NO_KEY_PROP;
@Override
public String getKey() {
return name();
}
}
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPADBAdaptorException(final Throwable e, final HttpStatusCode statusCode) {
super(e, statusCode);
}
public ODataJPADBAdaptorException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String... params) {
super(messageKey.getKey(), statusCode, cause, params);
}
public ODataJPADBAdaptorException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public ODataJPADBAdaptorException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final String... params) {
super(messageKey.getKey(), statusCode, params);
}
public ODataJPADBAdaptorException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) {
super(messageKey.getKey(), statusCode, e);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAIllegalAccessException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAIllegalAccessException.java | package com.sap.olingo.jpa.processor.core.exception;
/**
* The exception is thrown if a method got called that should not
*
* @author Oliver Grande
* Created: 03.07.2019
*
*/
public class ODataJPAIllegalAccessException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAInvocationTargetException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAInvocationTargetException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
/*
* This exception is thrown when an exception occurs in a jpa pojo method
*/
public class ODataJPAInvocationTargetException extends ODataJPAProcessException { // NOSONAR
private static final long serialVersionUID = 2410838419178517426L;
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
private final String path;
public ODataJPAInvocationTargetException(final Throwable e, final String path) {
super(e, HttpStatusCode.BAD_REQUEST);
this.path = path;
}
public ODataJPAInvocationTargetException(final Throwable e) {
super(e, HttpStatusCode.BAD_REQUEST);
this.path = null;
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
public String getPath() {
return path;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAIllegalArgumentException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAIllegalArgumentException.java | package com.sap.olingo.jpa.processor.core.exception;
public class ODataJPAIllegalArgumentException extends RuntimeException {
private static final long serialVersionUID = 8012137500100028346L;
private final String[] params;
public ODataJPAIllegalArgumentException(final Throwable cause) {
super(cause);
params = new String[0];
}
public ODataJPAIllegalArgumentException(final String... params) {
super();
this.params = params;
}
public String[] getParams() {
return params;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAProcessorException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAProcessorException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
/*
* Copied from org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPAModelException
* See also org.apache.olingo.odata2.jpa.processor.core.exception.ODataJPAMessageServiceDefault
*/
public class ODataJPAProcessorException extends ODataJPAProcessException { // NOSONAR
/**
*
*/
private static final long serialVersionUID = -7188499882306858747L;
public enum MessageKeys implements ODataJPAMessageKey {
QUERY_PREPARATION_ERROR,
QUERY_RESULT_CONV_ERROR,
QUERY_RESULT_URI_ERROR,
QUERY_SERVER_DRIVEN_PAGING_NOT_IMPLEMENTED,
QUERY_SERVER_DRIVEN_PAGING_GONE,
BATCH_CHANGE_SET_NOT_IMPLEMENTED,
NOT_SUPPORTED_CREATE,
NOT_SUPPORTED_UPDATE,
NOT_SUPPORTED_UPDATE_VALUE,
NOT_SUPPORTED_DELETE,
NOT_SUPPORTED_DELETE_VALUE,
NOT_SUPPORTED_RESOURCE_TYPE,
NOT_SUPPORTED_FUNC_WITH_NAVI,
NOT_SUPPORTED_PROP_TYPE,
NOT_SUPPORTED_COUNT,
PARAMETER_NULL,
WRONG_RETURN_TYPE,
RETURN_NULL,
RETURN_MISSING_ENTITY,
ATTRIBUTE_RETRIEVAL_FAILED,
ATTRIBUTE_NOT_FOUND,
ODATA_MAXPAGESIZE_NOT_A_NUMBER,
SETTER_NOT_FOUND,
GETTER_NOT_FOUND,
NO_COLLECTION_RETURNED_BY_GETTER,
BEFORE_IMAGE_MERGED,
ENTITY_TYPE_UNKNOWN,
FUNCTION_UNKNOWN,
ACTION_UNKNOWN,
ENUMERATION_UNKNOWN,
NO_METADATA_PROVIDER,
EXPAND_NON_SUPPORTED_EXPAND,
EXPAND_NON_SUPPORTED_AT_ALL,
EXPAND_EXCEEDS_MAX_LEVEL,
VALIDATION_NOT_POSSIBLE_TOO_MANY_RESULTS,
COUNT_NON_SUPPORTED_COUNT;
@Override
public String getKey() {
return name();
}
}
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPAProcessorException(final Throwable exception, final HttpStatusCode statusCode) {
super(exception, statusCode);
}
public ODataJPAProcessorException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String... params) {
super(messageKey.getKey(), statusCode, cause, params);
}
public ODataJPAProcessorException(final String messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String[] params) {
super(messageKey, statusCode, cause, params);
}
public ODataJPAProcessorException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public ODataJPAProcessorException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final String... params) {
super(messageKey.getKey(), statusCode, params);
}
public ODataJPAProcessorException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable exception) {
super(messageKey.getKey(), statusCode, exception);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPATransactionException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPATransactionException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
public class ODataJPATransactionException extends ODataJPAProcessException { // NOSONAR
private static final long serialVersionUID = -3720990003700857965L;
private static final String MESSAGE_KEY = "CANNOT_CREATE_NEW_TRANSACTION";
public ODataJPATransactionException(final Throwable cause) {
super(cause, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
public ODataJPATransactionException() {
super(MESSAGE_KEY, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
public ODataJPATransactionException(final Exception e) {
super(MESSAGE_KEY, HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
@Override
protected String getBundleName() {
return null;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPANotImplementedException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPANotImplementedException.java | package com.sap.olingo.jpa.processor.core.exception;
import static org.apache.olingo.commons.api.http.HttpStatusCode.NOT_IMPLEMENTED;
/*
* This exception is thrown when an exception occurs in a jpa pojo method
*/
public class ODataJPANotImplementedException extends ODataJPAProcessException { // NOSONAR
private static final long serialVersionUID = 2410838419178517426L;
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPANotImplementedException(final String... params) {
super(NOT_IMPLEMENTED.name(), NOT_IMPLEMENTED, params);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAFilterException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPAFilterException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
public class ODataJPAFilterException extends ODataJPAProcessException {
/**
*
*/
private static final long serialVersionUID = -7188499882306858747L;
public enum MessageKeys implements ODataJPAMessageKey {
NOT_SUPPORTED_OPERATOR,
NOT_SUPPORTED_FILTER,
NOT_SUPPORTED_OPERATOR_TYPE,
NOT_SUPPORTED_FUNCTION_COLLECTION,
NOT_SUPPORTED_FUNCTION_NOT_SCALAR,
NOT_SUPPORTED_TRANSIENT,
NOT_ALLOWED_MEMBER,
FILTERING_REQUIRED,
FILTERING_NOT_SUPPORTED,
FILTERING_MISSING_PROPERTIES,
NO_VALUES_OUT_OF_LIMIT;
@Override
public String getKey() {
return name();
}
}
private static final String BUNDLE_NAME = "processor-exceptions-i18n";
public ODataJPAFilterException(final Throwable cause, final HttpStatusCode statusCode) {
super(cause, statusCode);
}
public ODataJPAFilterException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final Throwable cause, final String... params) {
super(messageKey.getKey(), statusCode, cause, params);
}
public ODataJPAFilterException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public ODataJPAFilterException(final MessageKeys messageKey, final HttpStatusCode statusCode,
final String... params) {
super(messageKey.getKey(), statusCode, params);
}
public ODataJPAFilterException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) {
super(messageKey.getKey(), statusCode, e);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPACollectionProperty.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPACollectionProperty.java | package com.sap.olingo.jpa.processor.core.properties;
public interface JPACollectionProperty extends JPAProcessorAttribute {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAOrderByPropertyFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAOrderByPropertyFactory.java | package com.sap.olingo.jpa.processor.core.properties;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.apache.olingo.server.api.uri.queryoption.OrderByItem;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.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.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.core.exception.ODataJPAIllegalArgumentException;
public class JPAOrderByPropertyFactory {
/**
*
* @param orderByItem
* @param et
* @return
* @throws ODataJPAIllegalArgumentException
*/
public JPAProcessorAttribute createProperty(final OrderByItem orderByItem, final JPAEntityType et,
final Locale locale) {
try {
final var orderInfo = extractOrderInfo(et, orderByItem);
return createProperty(orderByItem, locale, orderInfo);
} catch (final ODataJPAModelException e) {
throw new ODataJPAIllegalArgumentException(orderByItem.getExpression().toString());
}
}
public JPAProcessorAttribute createProperty(final From<?, ?> target, final JPAPath path, final CriteriaBuilder cb) {
final var orderByAttribute = new JPAProcessorSimpleAttributeImpl(path, Collections.emptyList(), false);
return orderByAttribute.setTarget(target, Collections.emptyMap(), cb);
}
private OrderInfo extractOrderInfo(final JPAEntityType et, final OrderByItem orderByItem)
throws ODataJPAModelException {
final List<JPAAssociationPath> hops = new ArrayList<>();
var path = new StringBuilder();
JPAStructuredType type = et;
if (orderByItem.getExpression() instanceof final Member member) {
for (final var part : member.getResourcePath().getUriResourceParts()) {
if (part instanceof final UriResourceProperty property) {
if (property.isCollection()) {
path.append(property.getProperty().getName());
final var associationPath = ((JPACollectionAttribute) getJPAPath(type, path.toString()).getLeaf())
.asAssociation();
type = associationPath.getTargetType();
hops.add(associationPath);
path = new StringBuilder();
} else {
path.append(property.getProperty().getName()).append(JPAPath.PATH_SEPARATOR);
}
} else if (part instanceof final UriResourceNavigation navigation) {
path.append(navigation.getProperty().getName());
final var associationPath = type.getAssociationPath(path.toString());
type = associationPath.getTargetType();
hops.add(associationPath);
path = new StringBuilder();
}
}
} else {
// TODO Support methods like tolower for order by as well
throw new ODataJPAIllegalArgumentException(orderByItem.getExpression().toString());
}
return new OrderInfo(hops, path, type);
}
private JPAProcessorAttribute createProperty(final OrderByItem orderByItem, final Locale locale,
final OrderInfo orderInfo) throws ODataJPAModelException {
switch (getKindOfLastPart(orderByItem)) {
case primitiveProperty:
final var pathString = orderInfo.path.deleteCharAt(orderInfo.path.length() - 1).toString();
final var lastType = orderInfo.type;
return Optional.ofNullable(lastType.getPath(pathString))
.filter(attribute -> attribute.getLeaf() instanceof JPADescriptionAttribute)
.map(attribute -> createDescriptionProperty(orderByItem, orderInfo.hops, attribute, locale))
.or(() -> this.createPrimitiveProperty(orderByItem, orderInfo.hops, pathString, lastType))
.orElseThrow(() -> new ODataJPAIllegalArgumentException(orderByItem.getExpression().toString()));
case count:
return new JPAProcessorCountAttributeImpl(orderInfo.hops, orderByItem.isDescending());
default:
throw new ODataJPAIllegalArgumentException(orderByItem.getExpression().toString());
}
}
private JPAProcessorAttribute createDescriptionProperty(final OrderByItem orderByItem,
final List<JPAAssociationPath> hops, final JPAPath attribute, final Locale locale) {
return new JPAProcessorDescriptionAttributeImpl(attribute, hops, orderByItem.isDescending(), locale);
}
private Optional<JPAProcessorAttribute> createPrimitiveProperty(final OrderByItem orderByItem,
final List<JPAAssociationPath> hops, final String pathString, final JPAStructuredType type) {
try {
return Optional.ofNullable(type.getPath(pathString))
.map(attribute -> new JPAProcessorSimpleAttributeImpl(attribute, hops, orderByItem.isDescending()));
} catch (final ODataJPAModelException e) {
return Optional.empty();
}
}
private UriResourceKind getKindOfLastPart(final OrderByItem orderByItem) {
final var parts = ((Member) orderByItem.getExpression()).getResourcePath().getUriResourceParts();
return parts.get(parts.size() - 1).getKind();
}
@Nonnull
private JPAPath getJPAPath(final JPAStructuredType st, final String name) {
try {
final var jpaPath = st.getPath(name);
if (jpaPath != null)
return jpaPath;
else
throw new ODataJPAIllegalArgumentException(name);
} catch (final ODataJPAModelException e) {
throw new ODataJPAIllegalArgumentException(e);
}
}
private static record OrderInfo(List<JPAAssociationPath> hops, StringBuilder path, JPAStructuredType type) {
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorAttribute.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorAttribute.java | package com.sap.olingo.jpa.processor.core.properties;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public interface JPAProcessorAttribute {
/**
*
* @return
*/
@Nonnull
String getAlias();
/**
* As of now transient properties are not sortable
* @return
*/
boolean isSortable();
/**
* @return True if sorting descending is required
*/
boolean sortDescending();
/**
* Indicates that a join is required to fulfill the request
* @return
*/
boolean requiresJoin();
/**
*
* @param target
* @param joinTables
* @param cb
* @return
*/
JPAProcessorAttribute setTarget(@Nonnull final From<?, ?> target, @Nonnull final Map<String, From<?, ?>> joinTables,
@Nonnull final CriteriaBuilder cb);
/**
* If required, a join with 'from' is generated. If a join is required can be checked with
* {@link #requiresJoin()}.<br>
* Requires that the target was already set via
* @param <T>
* @param <S>
* @return Null if no join is required
*/
<T, S> Join<T, S> createJoin();
/**
* Generates an order statement for this attribute.<br>
* Requires that {@link #createJoin(From, CriteriaBuilder)} was called before.
* @param cb
* @param groups
* @return
* @throws ODataJPAQueryException
*/
@Nonnull
Order createOrderBy(final CriteriaBuilder cb, final List<String> groups) throws ODataJPAQueryException;
/**
* Requires that {@link #setTarget(From, CriteriaBuilder)} was called before.
* @return
*/
Path<Object> getPath();
JPAPath getJPAPath();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorCountAttribute.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorCountAttribute.java | package com.sap.olingo.jpa.processor.core.properties;
public interface JPAProcessorCountAttribute extends JPAProcessorAttribute {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorDescriptionAttributeImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorDescriptionAttributeImpl.java | package com.sap.olingo.jpa.processor.core.properties;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADescriptionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
public class JPAProcessorDescriptionAttributeImpl extends JPAAbstractProcessorAttributeImpl implements
JPAProcessorDescriptionAttribute {
private final boolean sortDescending;
private final Locale locale;
private Optional<Path<Object>> criteriaPath;
private Optional<From<?, ?>> from;
public JPAProcessorDescriptionAttributeImpl(final JPAPath path, final List<JPAAssociationPath> hops,
final boolean descending, final Locale locale) {
super(path, hops);
this.sortDescending = descending;
this.locale = locale;
this.criteriaPath = Optional.empty();
this.from = Optional.empty();
if (hops.size() > 1)
throw new ODataJPAIllegalArgumentException(path.getAlias());
}
@Override
public String getAlias() {
return path.getAlias();
}
@Override
public boolean isSortable() {
return true;
}
@Override
public boolean sortDescending() {
return sortDescending;
}
@Override
public boolean requiresJoin() {
return true;
}
@Override
public Path<Object> getPath() {
if (criteriaPath.isEmpty()) {
criteriaPath = Optional.of(
from.orElseThrow(IllegalAccessError::new)
.get(((JPADescriptionAttribute) path.getLeaf()).getDescriptionAttribute().getInternalName()));
}
return criteriaPath.get();
}
@Override
public JPAProcessorAttribute setTarget(final From<?, ?> target, final Map<String, From<?, ?>> joinTables,
final CriteriaBuilder cb) {
determineFrom(target, cb, joinTables);
return this;
}
@SuppressWarnings("unchecked")
@Override
public <T, S> Join<T, S> createJoin() {
return (Join<T, S>) from.orElseThrow(IllegalAccessError::new);
}
@SuppressWarnings("unchecked")
void determineFrom(final From<?, ?> target, final CriteriaBuilder cb,
final Map<String, From<?, ?>> joinTables) throws IllegalAccessError {
from = Optional.of(
joinTables.containsKey(getAlias())
? (From<Object, Object>) joinTables.get(getAlias())
: (From<Object, Object>) createJoinFromPath(target, cb));
}
@SuppressWarnings("unchecked")
From<Object, Object> createJoinFromPath(final From<?, ?> target, final CriteriaBuilder cb) {
final JPADescriptionAttribute descriptionField = ((JPADescriptionAttribute) path.getLeaf());
final var parentFrom = (!hops.isEmpty())
? createJoinFromPath(hops.get(0).getAlias(), hops.get(0).getPath(), target, JoinType.LEFT)
: target;
final Join<?, ?> join = createJoinFromPath(getAlias(), path.getPath(), parentFrom, JoinType.LEFT);
if (descriptionField.isLocationJoin()) {
join.on(createOnCondition(join, descriptionField, locale.toString(), cb));
} else {
join.on(createOnCondition(join, descriptionField, locale.getLanguage(), cb));
}
return (From<Object, Object>) join;
}
private Expression<Boolean> createOnCondition(final Join<?, ?> join, final JPADescriptionAttribute descriptionField,
final String localValue, final CriteriaBuilder cb) {
final Predicate existingOn = join.getOn();
Expression<Boolean> result = cb.equal(determinePath(join, descriptionField.getLocaleFieldName()), localValue);
if (existingOn != null) {
result = cb.and(existingOn, result);
}
for (final var value : descriptionField.getFixedValueAssignment().entrySet()) {
result = cb.and(result,
cb.equal(determinePath(join, value.getKey()), value.getValue()));
}
return result;
}
private Expression<?> determinePath(final Join<?, ?> join, final JPAPath jpaPath) {
Path<?> attributePath = join;
for (final JPAElement pathElement : jpaPath.getPath()) {
attributePath = attributePath.get(pathElement.getInternalName());
}
return attributePath;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorNavigationAttribute.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorNavigationAttribute.java | package com.sap.olingo.jpa.processor.core.properties;
public interface JPAProcessorNavigationAttribute extends JPAProcessorAttribute {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorSimpleAttributeImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorSimpleAttributeImpl.java | package com.sap.olingo.jpa.processor.core.properties;
import static com.sap.olingo.jpa.processor.core.query.ExpressionUtility.convertToCriteriaPath;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Path;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAIllegalArgumentException;
class JPAProcessorSimpleAttributeImpl extends JPAAbstractProcessorAttributeImpl implements JPAProcessorSimpleAttribute {
private final boolean sortDescending;
private Optional<Path<Object>> criteriaPath;
private Optional<From<?, ?>> from;
JPAProcessorSimpleAttributeImpl(final JPAPath path, final List<JPAAssociationPath> hops, final boolean descending) {
super(path, hops);
this.sortDescending = descending;
this.criteriaPath = Optional.empty();
this.from = Optional.empty();
if (hops.size() > 1)
throw new ODataJPAIllegalArgumentException(path.getAlias());
}
@Override
public String getAlias() {
return hops.isEmpty() ? path.getAlias() : hops.get(0).getAlias();
}
@Override
public boolean isSortable() {
return !path.isTransient();
}
@Override
public boolean sortDescending() {
return sortDescending;
}
@Override
public JPAProcessorAttribute setTarget(final From<?, ?> target, final Map<String, From<?, ?>> joinTables,
final CriteriaBuilder cb) {
determineFrom(target, joinTables);
return this;
}
@SuppressWarnings("unchecked")
@Override
public <T, S> Join<T, S> createJoin() {
return requiresJoin()
? (Join<T, S>) from.orElseThrow(IllegalAccessError::new)
: null;
}
@Override
public Path<Object> getPath() {
if (criteriaPath.isEmpty()) {
criteriaPath = Optional.of(convertToCriteriaPath(
from.orElseThrow(IllegalAccessError::new),
path.getPath()));
criteriaPath.get().alias(path.getAlias());
}
return criteriaPath.get();
}
void determineFrom(final From<?, ?> target, final Map<String, From<?, ?>> joinTables) {
from = Optional.of(requiresJoin()
? asJoin(target, joinTables)
: target);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorCountAttributeImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorCountAttributeImpl.java | package com.sap.olingo.jpa.processor.core.properties;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ORDER_BY_TRANSIENT;
import static org.apache.olingo.commons.api.http.HttpStatusCode.NOT_IMPLEMENTED;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Order;
import jakarta.persistence.criteria.Path;
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.processor.core.exception.ODataJPAIllegalArgumentException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
class JPAProcessorCountAttributeImpl extends JPAAbstractProcessorAttributeImpl implements JPAProcessorCountAttribute {
private final boolean descending;
private Optional<From<?, ?>> from;
JPAProcessorCountAttributeImpl(final List<JPAAssociationPath> hops, final boolean descending) {
super(null, hops);
this.descending = descending;
this.from = Optional.empty();
if (hops.size() > 1)
throw new ODataJPAIllegalArgumentException(hops.get(1).getAlias());
}
@Override
public String getAlias() {
return hops.isEmpty() ? "Count" : hops.get(0).getAlias();
}
@Override
public boolean isSortable() {
return !hops.isEmpty() && !hops.get(0).getLeaf().isTransient();
}
@Override
public boolean sortDescending() {
return descending;
}
@Override
public JPAProcessorAttribute setTarget(final From<?, ?> target, final Map<String, From<?, ?>> joinTables,
final CriteriaBuilder cb) {
determineFrom(target, joinTables);
return this;
}
@SuppressWarnings("unchecked")
@Override
public <T, S> Join<T, S> createJoin() {
return requiresJoin()
? (Join<T, S>) from.orElseThrow(IllegalAccessError::new)
: null;
}
@Override
public Path<Object> getPath() {
if (from.isEmpty())
throw new IllegalAccessError();
return null;
}
@Override
public Order createOrderBy(final CriteriaBuilder cb, final List<String> groups) throws ODataJPAQueryException {
if (isTransient())
throw new ODataJPAQueryException(QUERY_PREPARATION_ORDER_BY_TRANSIENT, NOT_IMPLEMENTED, hops.get(0).getAlias());
return addOrderByExpression(cb, sortDescending(), cb.count(from.get()));
}
private boolean isTransient() {
for (final var hop : hops) {
for (final var part : hop.getPath()) {
if (part instanceof final JPAAttribute attribute
&& attribute.isTransient())
return true;
}
}
return false;
}
void determineFrom(final From<?, ?> target, final Map<String, From<?, ?>> joinTables) {
from = Optional.of(requiresJoin()
? asJoin(target, joinTables)
: target);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorDescriptionAttribute.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorDescriptionAttribute.java | package com.sap.olingo.jpa.processor.core.properties;
public interface JPAProcessorDescriptionAttribute extends JPAProcessorAttribute {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorSimpleAttribute.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAProcessorSimpleAttribute.java | package com.sap.olingo.jpa.processor.core.properties;
public interface JPAProcessorSimpleAttribute extends JPAProcessorAttribute {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAAbstractProcessorAttributeImpl.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/properties/JPAAbstractProcessorAttributeImpl.java | package com.sap.olingo.jpa.processor.core.properties;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_NOT_ALLOWED_MEMBER;
import static com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ORDER_BY_TRANSIENT;
import static org.apache.olingo.commons.api.http.HttpStatusCode.BAD_REQUEST;
import static org.apache.olingo.commons.api.http.HttpStatusCode.FORBIDDEN;
import java.util.List;
import java.util.Map;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Order;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
abstract class JPAAbstractProcessorAttributeImpl implements JPAProcessorAttribute {
final JPAPath path;
final List<JPAAssociationPath> hops;
JPAAbstractProcessorAttributeImpl(final JPAPath path, final List<JPAAssociationPath> hops) {
super();
this.path = path;
this.hops = hops;
}
<T, S> Join<T, S> createJoinFromPath(final String alias, final List<JPAElement> pathList,
final From<T, S> root, final JoinType finalJoinType) {
Join<T, S> join = null;
JoinType joinType;
for (int i = 0; i < pathList.size(); i++) {
if (i == pathList.size() - 1) {
joinType = finalJoinType;
} else {
joinType = JoinType.INNER;
}
if (i == 0) {
join = root.join(pathList.get(i).getInternalName(), joinType);
join.alias(alias);
} else if (i < pathList.size()) {
join = join.join(pathList.get(i).getInternalName(), joinType);
join.alias(pathList.get(i).getExternalName());
}
}
return join;
}
Order addOrderByExpression(final CriteriaBuilder cb, final boolean isDescending,
final Expression<?> expression) {
return isDescending ? cb.desc(expression) : cb.asc(expression);
}
@SuppressWarnings("unchecked")
From<Object, Object> asJoin(final From<?, ?> target, final Map<String, From<?, ?>> joinTables) {
return joinTables.containsKey(getAlias())
? (From<Object, Object>) joinTables.get(getAlias())
: (From<Object, Object>) createJoinFromPath(getAlias(), hops.get(0).getPath(), target, JoinType.LEFT);
}
@Override
public Order createOrderBy(final CriteriaBuilder cb, final List<String> groups) throws ODataJPAQueryException {
if (path.isTransient())
throw new ODataJPAQueryException(QUERY_PREPARATION_ORDER_BY_TRANSIENT, BAD_REQUEST, path
.getLeaf().toString());
if (!path.isPartOfGroups(groups)) {
throw new ODataJPAQueryException(QUERY_PREPARATION_NOT_ALLOWED_MEMBER, FORBIDDEN, path.getAlias());
}
return addOrderByExpression(cb, sortDescending(), getPath());
}
@Override
public boolean requiresJoin() {
return !hops.isEmpty();
}
@Override
public JPAPath getJPAPath() {
return path;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataServiceContextBuilder.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataServiceContextBuilder.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.processor.ErrorProcessor;
import com.sap.olingo.jpa.metadata.api.JPAApiVersion;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
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.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext.Builder;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
public interface JPAODataServiceContextBuilder {
JPAODataSessionContextAccess build() throws ODataException;
/**
* A database processor allows database specific implementations for search and odata function with function import
* that are implemented as database functions.<br>
* In case no database processor is provided and non could be determined via an data source
* {@link JPADefaultDatabaseProcessor} is used.
* @param databaseProcessor
* @return
*/
JPAODataServiceContextBuilder setDatabaseProcessor(JPAODataDatabaseProcessor databaseProcessor);
/**
* The data source is used to create an entity manager factory if not provided, see
* {@link Builder#setEntityManagerFactory(EntityManagerFactory)}, and to determine the type of
* database used to select an integrated database processor, in case the database processor was not set via
* {@link Builder#setDatabaseProcessor(JPAODataDatabaseProcessor)}}.
* @param ds
* @return
*/
JPAODataServiceContextBuilder setDataSource(DataSource ds);
/**
* Allows to provide an Olingo error processor. The error processor allows to enrich an error response. See
* <a
* href=
* "http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata03/os/odata-json-format-v4.0-errata03-os-complete.html#_Toc453766668"
* >JSON Error Response</a> or
* <a
* href=
* "http://docs.oasis-open.org/odata/odata-atom-format/v4.0/cs02/odata-atom-format-v4.0-cs02.html#_Toc372792829">Atom
* Error Response</a>.
* @param errorProcessor
*/
JPAODataServiceContextBuilder setErrorProcessor(ErrorProcessor errorProcessor);
/**
*
* @param postProcessor
* @return
*/
JPAODataServiceContextBuilder setMetadataPostProcessor(JPAEdmMetadataPostProcessor postProcessor);
/**
*
* @param jpaOperationConverter
* @return
*/
JPAODataServiceContextBuilder setOperationConverter(JPAODataDatabaseOperations jpaOperationConverter);
/**
* Register a provider that is able to decides based on a given query if the server like to return only a sub set of
* the requested results as well as a $skiptoken.
* @param provider
*/
JPAODataServiceContextBuilder setPagingProvider(JPAODataPagingProvider provider);
/**
* The name of the persistence-unit to be used. It is taken to create a entity manager factory
* ({@link Builder#setEntityManagerFactory(EntityManagerFactory)}), if not provided and
* as namespace of the OData service, in case the default name builder shall be used.
* @param pUnit
* @return
*/
JPAODataServiceContextBuilder setPUnit(String pUnit);
/**
*
* @param references
* @return
*/
JPAODataServiceContextBuilder setReferences(List<EdmxReference> references);
/**
* Name of the top level package to look for
* <ul>
* <li>Enumeration Types
* <li>Java class based Functions
* </ul>
* @param packageName
*/
JPAODataServiceContextBuilder setTypePackage(String... packageName);
JPAODataServiceContextBuilder setRequestMappingPath(String mappingPath);
/**
* Set an externally created entity manager factory.<br>
* This is necessary e.g. in case a spring based service shall run without a <code>persistance.xml</code>.
* @param emf
* @return
*/
JPAODataServiceContextBuilder setEntityManagerFactory(EntityManagerFactory emf);
/**
* Set a custom EDM name builder {@link JPAEdmNameBuilder}. If non is provided {@link JPADefaultEdmNameBuilder} is
* used, which uses the provided persistence-unit name ({@link JPAODataServiceContext.Builder#setPUnit}) as
* namespace.
* @param nameBuilder
* @return
*/
JPAODataServiceContextBuilder setEdmNameBuilder(JPAEdmNameBuilder nameBuilder);
<T extends JPAODataBatchProcessor> JPAODataServiceContextBuilder setBatchProcessorFactory(
JPAODataBatchProcessorFactory<T> batchProcessorFactory);
/**
* Some clients, like Excel, require context url's with an absolute path. The default generation of relative paths
* can be overruled.<br>
* @see <a href="https://issues.apache.org/jira/browse/OLINGO-787">Issue OLINGO-787</a>
* @param useAbsoluteContextURL
*/
JPAODataServiceContextBuilder setUseAbsoluteContextURL(boolean useAbsoluteContextURL);
JPAODataServiceContextBuilder setAnnotationProvider(AnnotationProvider... annotationProvider);
/**
*
*/
JPAODataQueryDirectivesBuilder useQueryDirectives();
/**
* Some database use different clauses for a certain function. E.g., to limit the number of rows returned.
* Some databases use LIMIT and OFFSET, other OFFSET ... ROWS and FETCH NEXT ... ROWS.<br>
* This is relevant when module <i>odata-jpa-processor-cb</i> is used.
* @since 2.2.0
*/
JPAODataServiceContextBuilder setSqlPatternProvider(ProcessorSqlPatternProvider sqlPattern);
/**
* Set an API version. If no version is provided, a version is created from the corresponding setters.
* @see <a href=
* "https://github.com/SAP/olingo-jpa-processor-v4/blob/main/jpa-tutorial/Questions/HowToHandleApiVersions.adoc">How
* to handle API versions?<a>
* @param apiVersion
* @return
* @since 2.3.0
*/
JPAODataServiceContextBuilder setVersions(JPAApiVersion... apiVersions);
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataApiVersion.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataApiVersion.java | package com.sap.olingo.jpa.processor.core.api;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import jakarta.persistence.EntityManagerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import com.sap.olingo.jpa.metadata.api.JPAApiVersion;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
class JPAODataApiVersion implements JPAODataApiVersionAccess {
private static final Log LOGGER = LogFactory.getLog(JPAODataApiVersion.class);
private final String id;
private final JPAEdmProvider edmProvider;
private final EntityManagerFactory emf;
private String mappingPath;
JPAODataApiVersion(final JPAApiVersion version, final JPAEdmNameBuilder nameBuilder,
final List<AnnotationProvider> annotationProviders, final ProcessorSqlPatternProvider sqlPattern)
throws ODataException {
this.id = version.getId();
this.edmProvider = createEdmProvider(version, nameBuilder, annotationProviders);
this.emf = createEmfWrapper(version.getEntityManagerFactory(), edmProvider, sqlPattern);
this.mappingPath = version.getRequestMappingPath();
}
JPAODataApiVersion(final String id, final JPAEdmProvider edmProvider, final EntityManagerFactory emf) {
this.id = id;
this.edmProvider = edmProvider;
this.emf = emf;
}
@Override
public String getId() {
return id;
}
@Override
public JPAEdmProvider getEdmProvider() {
return edmProvider;
}
@Override
public EntityManagerFactory getEntityManagerFactory() {
return emf;
}
@Override
public String getMappingPath() {
return mappingPath;
}
private JPAEdmProvider createEdmProvider(final JPAApiVersion version, final JPAEdmNameBuilder nameBuilder,
final List<AnnotationProvider> annotationProviders) throws ODataException {
return new JPAEdmProvider(version.getEntityManagerFactory().getMetamodel(), version.getMetadataPostProcessor(),
version.getPackageNames(), nameBuilder, annotationProviders);
}
@SuppressWarnings("unchecked")
private EntityManagerFactory createEmfWrapper(final EntityManagerFactory factory, final JPAEdmProvider jpaEdm,
final ProcessorSqlPatternProvider sqlPattern) {
try {
final Class<? extends EntityManagerFactory> wrapperClass = (Class<? extends EntityManagerFactory>) Class
.forName("com.sap.olingo.jpa.processor.cb.api.EntityManagerFactoryWrapper");
if (wrapperClass != null) {
LOGGER.trace("Criteria Builder Extension found. It will be used");
return wrapperClass.getConstructor(EntityManagerFactory.class,
JPAServiceDocument.class, ProcessorSqlPatternProvider.class)
.newInstance(factory, jpaEdm.getServiceDocument(), sqlPattern);
} else
return factory;
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
LOGGER.debug("Exception thrown while trying to create instance of emf wrapper", e);
} catch (final ClassNotFoundException e) {
// No Criteria Extension: everything is fine
LOGGER.trace("No Criteria Builder Extension found: use provided Entity Manager Factory");
}
return factory;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestContextAccess.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestContextAccess.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jakarta.persistence.EntityManager;
import org.apache.olingo.server.api.uri.UriInfoResource;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAHttpHeaderMap;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmQueryExtensionProvider;
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.JPAEntityType;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.serializer.JPASerializer;
public interface JPAODataRequestContextAccess {
public @Nonnull EntityManager getEntityManager();
public UriInfoResource getUriInfo();
public JPASerializer getSerializer();
public Optional<JPAODataClaimProvider> getClaimsProvider();
public Optional<JPAODataGroupProvider> getGroupsProvider();
public JPACUDRequestHandler getCUDRequestHandler();
public JPAServiceDebugger getDebugger();
public JPAODataTransactionFactory getTransactionFactory();
public Optional<EdmTransientPropertyCalculator<?>> getCalculator(@Nonnull final JPAAttribute transientProperty)
throws ODataJPAProcessorException;
public Optional<EdmQueryExtensionProvider> getQueryEnhancement(@Nonnull final JPAEntityType et)
throws ODataJPAProcessorException;
public @Nonnull JPAHttpHeaderMap getHeader();
public @Nonnull JPARequestParameterMap getRequestParameter();
public JPAODataDatabaseProcessor getDatabaseProcessor();
public @Nonnull JPAEdmProvider getEdmProvider() throws ODataJPAProcessorException;
public JPAODataDatabaseOperations getOperationConverter();
/**
*
* @return most significant locale. Used e.g. for description properties
*/
public @CheckForNull Locale getLocale();
/**
*
* @return list of locale provided for this request
*/
public List<Locale> getProvidedLocale();
public JPAODataQueryDirectives getQueryDirectives();
public JPAODataEtagHelper getEtagHelper();
public Optional<JPAODataPagingProvider> getPagingProvider();
public JPAODataPathInformation getPathInformation();
public String getMappingPath();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAErrorProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAErrorProcessor.java | package com.sap.olingo.jpa.processor.core.api;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataServerError;
public interface JPAErrorProcessor {
public void processError(final ODataRequest request, final ODataServerError serverError);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessor.java | package com.sap.olingo.jpa.processor.core.api;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.RollbackException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.format.PreferenceName;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.batch.BatchFacade;
import org.apache.olingo.server.api.deserializer.batch.BatchOptions;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.apache.olingo.server.api.prefer.Preferences;
import org.apache.olingo.server.api.processor.BatchProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory.JPAODataTransaction;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPATransactionException;
/**
*
* <a href=
* "https://docs.oasis-open.org/odata/odata/v4.0/os/part1-protocol/odata-v4.0-os-part1-protocol.html#_Toc372793748">
* 11.7 Batch Requests </a>
*
* @author Oliver Grande
*
*/
public class JPAODataBatchProcessor implements BatchProcessor {
protected final JPAODataRequestContextAccess requestContext;
protected final JPAODataSessionContextAccess serviceContext;
protected OData odata;
protected ServiceMetadata serviceMetadata;
public JPAODataBatchProcessor(final JPAODataSessionContextAccess serviceContext,
final JPAODataRequestContextAccess requestContext) {
this.requestContext = requestContext;
this.serviceContext = serviceContext;
}
@Override
public final void init(final OData odata, final ServiceMetadata serviceMetadata) {
this.odata = odata;
this.serviceMetadata = serviceMetadata;
}
@Override
public final void processBatch(final BatchFacade facade, final ODataRequest request, final ODataResponse response)
throws ODataApplicationException, ODataLibraryException {
try (JPARuntimeMeasurement measurement = requestContext.getDebugger().newMeasurement(this, "processBatch")) {
final String boundary = facade.extractBoundaryFromContentType(request.getHeader(HttpHeader.CONTENT_TYPE));
final BatchOptions options = BatchOptions.with()
.rawBaseUri(request.getRawBaseUri())
.rawServiceResolutionUri(request.getRawServiceResolutionUri())
.build();
final List<BatchRequestPart> requestParts = odata.createFixedFormatDeserializer()
.parseBatchRequest(request.getBody(), boundary, options);
final List<ODataResponsePart> responseParts = executeBatchParts(facade, requestParts,
continueOnError(odata.createPreferences(request.getHeaders(HttpHeader.PREFER))));
final String responseBoundary = "batch_" + UUID.randomUUID().toString();
final InputStream responseContent = odata.createFixedFormatSerializer().batchResponse(responseParts,
responseBoundary);
response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responseBoundary);
response.setContent(responseContent);
response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
}
}
protected List<ODataResponsePart> executeBatchParts(final BatchFacade facade,
final List<BatchRequestPart> requestParts, final boolean continueOnError) throws ODataApplicationException,
ODataLibraryException {
final List<ODataResponsePart> responseParts = new ArrayList<>(requestParts.size());
for (final BatchRequestPart part : requestParts) {
final ODataResponsePart resp = facade.handleBatchRequest(part);
responseParts.add(resp);
final List<ODataResponse> responses = resp.getResponses();
responses.get(responses.size() - 1).getStatusCode();
if (requestHasFailed(responses) && !continueOnError)
return responseParts;
}
return responseParts;
}
/**
* Processing one change set of a $batch request.
* <p>
* <i>OData Version 4.0 Part 1: Protocol Plus Errata 02 11.7.4 Responding
* to a Batch Request</i> states: <br>
* <cite>All operations in a change set represent a single change unit so a
* service MUST successfully process and apply all the requests in the
* change set or else apply none of them. It is up to the service
* implementation to define rollback semantics to undo any requests
* within a change set that may have been applied before another request
* in that same change set failed and thereby apply this all-or-nothing
* requirement. The service MAY execute the requests within a change set
* in any order and MAY return the responses to the individual requests
* in any order. The service MUST include the Content-ID header in each
* response with the same value that the client specified in the
* corresponding request, so clients can correlate requests and
* responses.</cite>
* <p>
* This requires that the batch processor can create transactions. To do so it takes an instance of
* {@link JPAODataTransactionFactory } from the request context and requests a new transaction. In case this is not
* possible a exception with http status code 501 <i>Not Implemented</i> will be raised.
*/
@Override
public final ODataResponsePart processChangeSet(final BatchFacade facade, final List<ODataRequest> requests)
throws ODataApplicationException, ODataLibraryException {
/*
* To keep things simple, we dispatch the requests within the Change Set
* to the other processor interfaces.
*/
final List<ODataResponse> responses = new ArrayList<>();
try (JPARuntimeMeasurement measurement = requestContext.getDebugger().newMeasurement(this, "processChangeSet")) {
final JPAODataTransaction t = requestContext.getTransactionFactory().createTransaction();
try {
for (final ODataRequest request : requests) {
// Actual request dispatching to the other processor interfaces.
final ODataResponse response = facade.handleODataRequest(request);
// Determine if an error occurred while executing the request.
// Exceptions thrown by the processors get caught and result in
// a proper OData response.
final int statusCode = response.getStatusCode();
if (statusCode < HttpStatusCode.BAD_REQUEST.getStatusCode()) {
// The request has been executed successfully. Return the
// response as a part of the change set
responses.add(response);
} else {
t.rollback();
/*
* In addition the response must be provided as follows:
*
* OData Version 4.0 Part 1: Protocol Plus Errata 02 11.7.4
* Responding to a Batch Request
*
* When a request within a change set fails, the change set
* response is not represented using the multipart/mixed
* media type. Instead, a single response, using the
* application/http media type and a
* Content-Transfer-Encoding header with a value of binary,
* is returned that applies to all requests in the change
* set and MUST be formatted according to the Error Handling
* defined for the particular response format.
*
* This can be simply done by passing the response of the
* failed ODataRequest to a new instance of
* ODataResponsePart and setting the second parameter
* "isChangeSet" to false.
*/
return new ODataResponsePart(response, false);
}
}
requestContext.getCUDRequestHandler().validateChanges(requestContext.getEntityManager());
t.commit();
return new ODataResponsePart(responses, true);
} catch (ODataApplicationException | ODataLibraryException e) {
// In case of ODataLibraryException the batch request is malformed or the processor implementation is not
// correct. Throwing an exception will stop the whole batch request not only the Change Set!
t.rollback();
throw e;
} catch (final RollbackException e) {
if (e.getCause() instanceof OptimisticLockException) {
throw new ODataJPAProcessorException(e.getCause().getCause(), HttpStatusCode.PRECONDITION_FAILED);
}
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
} catch (final ODataJPATransactionException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.NOT_IMPLEMENTED);
}
}
/**
* OData Version 4.0 Part 1: Protocol Plus Errata 02 11.7.2 Batch Request Body states:
* <p>
* <cite>
* The service MUST process the requests within a batch request sequentially. Processing stops on the first error
* unless the odata.continue-on-error preference is specified. </cite>
* <p>
*
* <i>odata.continue-on-error</i> is explained in OData Version 4.0 Part 1: Protocol Plus Errata 02 8.2.8.3 Preference
* odata.continue-on-error and states:
* <p>
* <cite>
* The odata.continue-on-error preference on a batch request is used to request that, upon encountering a request
* within the batch that returns an error, the service return the error for that request and continue processing
* additional requests within the batch. The syntax of the odata.continue-on-error preference is specified in
* [OData-ABNF].
*
* If not specified, upon encountering an error the service MUST return the error within the batch and stop processing
* additional requests within the batch.
*
* A service MAY specify the support for the odata.continue-on-error preference using an annotation with term
* Capabilities.BatchContinueOnErrorSupported, see [OData-VocCap]. </cite>
* <p>
* So four cases have to be distinguished:
* <ul>
* <li>No header</li>
* <li>Header given without value</li>
* <li>Header given as true</li>
* <li>Header given as false</li>
* </ul>
* @param preferences
* @return
*/
final boolean continueOnError(final Preferences preferences) {
// Syntax: [ "odata." ] "continue-on-error" [ EQ-h booleanValue ] ; "true" / "false"
return Optional.ofNullable(preferences.getPreference(PreferenceName.CONTINUE_ON_ERROR.getName()))
.map(p -> p.getValue() == null ? Boolean.TRUE : Boolean.valueOf(p.getValue()))
.orElse(false);
}
private boolean requestHasFailed(final List<ODataResponse> responses) {
return responses.get(responses.size() - 1).getStatusCode() >= HttpStatusCode.BAD_REQUEST.getStatusCode();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataServiceContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataServiceContext.java | package com.sap.olingo.jpa.processor.core.api;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.processor.ErrorProcessor;
import com.sap.olingo.jpa.metadata.api.JPAApiVersion;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.JPAODataQueryDirectivesImpl;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseProcessorFactory;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException;
public final class JPAODataServiceContext implements JPAODataSessionContextAccess {
/**
*
*/
private static final Log LOGGER = LogFactory.getLog(JPAODataServiceContext.class);
private List<EdmxReference> references = new ArrayList<>();
private final JPAODataDatabaseOperations operationConverter;
private JPAEdmProvider jpaEdm;
private final JPAODataDatabaseProcessor databaseProcessor;
private final JPAEdmMetadataPostProcessor postProcessor;
private final String[] packageName;
private final ErrorProcessor errorProcessor;
private final JPAODataPagingProvider pagingProvider;
private final String namespace;
private final JPAODataBatchProcessorFactory<JPAODataBatchProcessor> batchProcessorFactory;
private final boolean useAbsoluteContextURL;
private final List<AnnotationProvider> annotationProvider;
private final JPAODataQueryDirectives queryDirectives;
private final ProcessorSqlPatternProvider sqlPattern;
private final Map<String, JPAODataApiVersionAccess> versions;
public static JPAODataServiceContextBuilder with() {
return new Builder();
}
@SuppressWarnings("unchecked")
private JPAODataServiceContext(final Builder builder) {
operationConverter = builder.operationConverter;
databaseProcessor = builder.databaseProcessor;
references = builder.references;
postProcessor = builder.postProcessor;
packageName = builder.packageNames;
errorProcessor = builder.errorProcessor;
pagingProvider = builder.pagingProvider;
jpaEdm = builder.jpaEdm;
namespace = builder.namespace;
batchProcessorFactory = (JPAODataBatchProcessorFactory<JPAODataBatchProcessor>) builder.batchProcessorFactory;
useAbsoluteContextURL = builder.useAbsoluteContextURL;
annotationProvider = Arrays.asList(builder.annotationProvider);
queryDirectives = builder.queryDirectives;
sqlPattern = builder.sqlPattern;
versions = builder.versions;
}
@Override
public JPAODataDatabaseProcessor getDatabaseProcessor() {
return databaseProcessor;
}
public JPAEdmProvider getEdmProvider(@Nonnull final EntityManager em) throws ODataException {
if (jpaEdm == null) {
Objects.nonNull(em);
jpaEdm = new JPAEdmProvider(this.namespace, em.getMetamodel(), postProcessor, packageName, annotationProvider);
}
return jpaEdm;
}
@Override
public ErrorProcessor getErrorProcessor() {
return this.errorProcessor == null ? new JPADefaultErrorProcessor() : this.errorProcessor;
}
@Override
public JPAODataDatabaseOperations getOperationConverter() {
return operationConverter;
}
@Override
public JPAODataPagingProvider getPagingProvider() {
return pagingProvider;
}
@Override
public List<EdmxReference> getReferences() {
return references;
}
@Override
public boolean useAbsoluteContextURL() {
return useAbsoluteContextURL;
}
@Override
public JPAODataBatchProcessorFactory<JPAODataBatchProcessor> getBatchProcessorFactory() {
return batchProcessorFactory;
}
@Override
public List<AnnotationProvider> getAnnotationProvider() {
return annotationProvider;
}
@Override
public JPAODataQueryDirectives getQueryDirectives() {
return queryDirectives;
}
@Override
public ProcessorSqlPatternProvider getSqlPatternProvider() {
return sqlPattern;
}
@Override
public JPAODataApiVersionAccess getApiVersion(final String id) {
return versions.get(id);
}
static class Builder implements JPAODataServiceContextBuilder {
private String namespace;
private List<EdmxReference> references = new ArrayList<>();
private JPAODataDatabaseOperations operationConverter = new JPADefaultDatabaseProcessor();
private JPAODataDatabaseProcessor databaseProcessor;
private JPAEdmMetadataPostProcessor postProcessor;
private String[] packageNames;
private ErrorProcessor errorProcessor;
private JPAODataPagingProvider pagingProvider;
private Optional<? extends EntityManagerFactory> emf = Optional.empty();
private DataSource dataSource;
private JPAEdmProvider jpaEdm;
private JPAEdmNameBuilder nameBuilder;
private String mappingPath;
private JPAODataBatchProcessorFactory<?> batchProcessorFactory;
private boolean useAbsoluteContextURL = false;
private AnnotationProvider[] annotationProvider;
private JPAODataQueryDirectivesImpl queryDirectives;
private ProcessorSqlPatternProvider sqlPattern;
private List<JPAApiVersion> apiVersions;
private final Map<String, JPAODataApiVersionAccess> versions;
private Builder() {
super();
apiVersions = List.of();
versions = new HashMap<>(2);
}
@Override
public JPAODataSessionContextAccess build() throws ODataException {
try {
createDefaultNameBuilder();
createDefaultAnnotationProvider();
createDefaultPackageNames();
createDefaultApiVersion();
convertApiVersion();
createDatabaseProcessor();
createDefaultBatchProcessorFactory();
createDefaultPagingProvider();
createDefaultQueryDirectives();
} catch (SQLException | PersistenceException e) {
throw new ODataJPAFilterException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
return new JPAODataServiceContext(this);
}
private void createDefaultPackageNames() {
if (packageNames == null)
packageNames = new String[0];
}
private void createDefaultBatchProcessorFactory() {
if (batchProcessorFactory == null) {
LOGGER.trace("No batch-processor-factory provided, use default factory to create one");
batchProcessorFactory = new JPADefaultBatchProcessorFactory();
}
}
private void createDefaultPagingProvider() {
if (pagingProvider == null)
pagingProvider = new JPADefaultPagingProvider();
}
private void createDefaultAnnotationProvider() {
if (annotationProvider == null || annotationProvider.length == 0) {
LOGGER.trace("No annotation provider provided, use default factory to create one");
annotationProvider = new AnnotationProvider[] {};
}
}
private void createDatabaseProcessor() throws SQLException {
if (databaseProcessor == null) {
LOGGER.trace("No database-processor provided, use JPAODataDatabaseProcessorFactory to create one");
databaseProcessor = new JPAODataDatabaseProcessorFactory().create(dataSource);
}
}
private void convertApiVersion() throws ODataException {
for (final var version : apiVersions)
versions.put(version.getId(), new JPAODataApiVersion(version, nameBuilder, Arrays.asList(annotationProvider),
sqlPattern));
}
private void createDefaultApiVersion() throws ODataJPAModelException {
if (apiVersions.isEmpty()) {
if (!emf.isPresent() && dataSource != null && namespace != null)
emf = Optional.ofNullable(JPAEntityManagerFactory.getEntityManagerFactory(namespace, dataSource));
if (emf.isPresent())
apiVersions = List.of(
JPAApiVersion.with()
.setId(JPAODataApiVersionAccess.DEFAULT_VERSION)
.setEntityManagerFactory(emf.get())
.setMetadataPostProcessor(postProcessor)
.setRequestMappingPath(mappingPath)
.setTypePackage(packageNames)
.build());
}
}
private void createDefaultNameBuilder() {
if (nameBuilder == null) {
LOGGER.trace("No name-builder provided, use JPADefaultEdmNameBuilder");
nameBuilder = new JPADefaultEdmNameBuilder(namespace);
}
}
private void createDefaultQueryDirectives() {
if (queryDirectives == null)
useQueryDirectives().build();
}
/**
* A database processor allows database specific implementations for search and odata function with function import
* that are implemented as database functions.<br>
* In case no database processor is provided and non could be determined via an data source
* {@link JPADefaultDatabaseProcessor} is used.
* @param databaseProcessor
* @return
*/
@Override
public JPAODataServiceContextBuilder setDatabaseProcessor(final JPAODataDatabaseProcessor databaseProcessor) {
this.databaseProcessor = databaseProcessor;
return this;
}
/**
* The data source is used to create an entity manager factory if not provided, see
* {@link Builder#setEntityManagerFactory(EntityManagerFactory)}, and to determine the type of
* database used to select an integrated database processor, in case the database processor was not set via
* {@link Builder#setDatabaseProcessor(JPAODataDatabaseProcessor)}}.
* @param dataSource
* @return
*/
@Override
public JPAODataServiceContextBuilder setDataSource(final DataSource dataSource) {
this.dataSource = dataSource;
return this;
}
/**
* Allows to provide an Olingo error processor. The error processor allows to enrich an error response. See
* <a
* href=
* "http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata03/os/odata-json-format-v4.0-errata03-os-complete.html#_Toc453766668"
* >JSON Error Response</a> or
* <a
* href=
* "http://docs.oasis-open.org/odata/odata-atom-format/v4.0/cs02/odata-atom-format-v4.0-cs02.html#_Toc372792829">Atom
* Error Response</a>.
* @param errorProcessor
*/
@Override
public JPAODataServiceContextBuilder setErrorProcessor(final ErrorProcessor errorProcessor) {
this.errorProcessor = errorProcessor;
return this;
}
/**
*
* @param postProcessor
* @return
*/
@Override
public JPAODataServiceContextBuilder setMetadataPostProcessor(final JPAEdmMetadataPostProcessor postProcessor) {
this.postProcessor = postProcessor;
return this;
}
/**
*
* @param jpaOperationConverter
* @return
*/
@Override
public JPAODataServiceContextBuilder setOperationConverter(final JPAODataDatabaseOperations jpaOperationConverter) {
this.operationConverter = jpaOperationConverter;
return this;
}
/**
* Register a provider that is able to decides based on a given query if the server like to return only a sub set of
* the requested results as well as a $skiptoken.
* @param provider
*/
@Override
public JPAODataServiceContextBuilder setPagingProvider(final JPAODataPagingProvider provider) {
this.pagingProvider = provider;
return this;
}
/**
* The name of the persistence-unit to be used. It is taken to create a entity manager factory
* ({@link Builder#setEntityManagerFactory(EntityManagerFactory)}), if not provided and
* as namespace of the OData service, in case the default name builder shall be used.
* @param pUnit
* @return
*/
@Override
public JPAODataServiceContextBuilder setPUnit(final String pUnit) {
this.namespace = pUnit;
return this;
}
/**
*
* @param references
* @return
*/
@Override
public JPAODataServiceContextBuilder setReferences(final List<EdmxReference> references) {
this.references = references;
return this;
}
/**
* Name of the top level package to look for
* <ul>
* <li>Enumeration Types
* <li>Java class based Functions
* </ul>
* @param packageName
*/
@Override
public JPAODataServiceContextBuilder setTypePackage(final String... packageName) {
this.packageNames = packageName;
return this;
}
@Override
public JPAODataServiceContextBuilder setRequestMappingPath(final String mappingPath) {
this.mappingPath = mappingPath;
return this;
}
/**
* Set an externally created entity manager factory.<br>
* This is necessary e.g. in case a spring based service shall run without a <code>persistance.xml</code>.
* @param emf
* @return
*/
@Override
public JPAODataServiceContextBuilder setEntityManagerFactory(final EntityManagerFactory emf) {
this.emf = Optional.of(emf);
return this;
}
/**
* Set a custom EDM name builder {@link JPAEdmNameBuilder}. If non is provided {@link JPADefaultEdmNameBuilder} is
* used, which uses the provided persistence-unit name ({@link JPAODataServiceContext.Builder#setPUnit}) as
* namespace.
* @param nameBuilder
* @return
*/
@Override
public JPAODataServiceContextBuilder setEdmNameBuilder(final JPAEdmNameBuilder nameBuilder) {
this.nameBuilder = nameBuilder;
return this;
}
@Override
public <T extends JPAODataBatchProcessor> JPAODataServiceContextBuilder setBatchProcessorFactory(
final JPAODataBatchProcessorFactory<T> batchProcessorFactory) {
this.batchProcessorFactory = batchProcessorFactory;
return this;
}
/**
* Some clients, like Excel, require context url's with an absolute path. The default generation of relative paths
* can be overruled.<br>
* @see <a href="https://issues.apache.org/jira/browse/OLINGO-787">Issue OLINGO-787</a>
* @param useAbsoluteContextURL
* @return
*/
@Override
public JPAODataServiceContextBuilder setUseAbsoluteContextURL(final boolean useAbsoluteContextURL) {
this.useAbsoluteContextURL = useAbsoluteContextURL;
return this;
}
@Override
public JPAODataServiceContextBuilder setAnnotationProvider(final AnnotationProvider... annotationProvider) {
this.annotationProvider = annotationProvider;
return this;
}
@Override
public JPAODataQueryDirectivesBuilder useQueryDirectives() {
return JPAODataQueryDirectives.with(this);
}
public JPAODataServiceContextBuilder setQueryDirectives(final JPAODataQueryDirectivesImpl queryDirectives) {
this.queryDirectives = queryDirectives;
return this;
}
@Override
public JPAODataServiceContextBuilder setSqlPatternProvider(final ProcessorSqlPatternProvider sqlPattern) {
this.sqlPattern = sqlPattern;
return this;
}
@Override
public JPAODataServiceContextBuilder setVersions(final JPAApiVersion... apiVersion) {
this.apiVersions = Arrays.asList(apiVersion);
return this;
}
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPair.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPair.java | package com.sap.olingo.jpa.processor.core.api;
/**
* Allows to provide a single value or a closed interval.<p>
* In case the min value is equals to {@linkplain JPAClaimsPair#ALL} the access is not restricted by this pair. This
* value has to be used independent from the type of the attribute used to protect an entity.
* @author Oliver Grande
*
* @param <T> Type of the attribute.
*/
public class JPAClaimsPair<T> {
public static final String ALL = "*";
public final T min;
public final T max;
public final boolean hasUpperBoundary;
public JPAClaimsPair(final T min) {
super();
this.min = min;
this.max = null;
this.hasUpperBoundary = false;
}
public JPAClaimsPair(final T min, final T max) {
super();
this.min = min;
this.max = max;
this.hasUpperBoundary = true;
}
@Override
public String toString() {
return "JPAClaimsPair [min=" + min + ", max=" + max + "]";
}
@SuppressWarnings("unchecked")
public <Y> Y minAs() {
return (Y) min;
}
@SuppressWarnings("unchecked")
public <Y> Y maxAs() {
return (Y) max;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestContext.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.server.api.debug.DebugSupport;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.processor.core.api.JPAODataExternalRequestContext.Builder;
public interface JPAODataRequestContext {
public static Builder with() {
return new Builder();
}
public EntityManager getEntityManager();
public Optional<JPAODataClaimProvider> getClaimsProvider();
public Optional<JPAODataGroupProvider> getGroupsProvider();
public JPACUDRequestHandler getCUDRequestHandler();
public DebugSupport getDebuggerSupport();
public JPAODataTransactionFactory getTransactionFactory();
public JPARequestParameterMap getRequestParameter();
public List<Locale> getLocales();
public String getVersion();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestProcessor.java | package com.sap.olingo.jpa.processor.core.api;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.RollbackException;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.processor.ActionPrimitiveProcessor;
import org.apache.olingo.server.api.processor.ActionVoidProcessor;
import org.apache.olingo.server.api.processor.ComplexCollectionProcessor;
import org.apache.olingo.server.api.processor.ComplexProcessor;
import org.apache.olingo.server.api.processor.CountComplexCollectionProcessor;
import org.apache.olingo.server.api.processor.CountEntityCollectionProcessor;
import org.apache.olingo.server.api.processor.CountPrimitiveCollectionProcessor;
import org.apache.olingo.server.api.processor.EntityProcessor;
import org.apache.olingo.server.api.processor.MediaEntityProcessor;
import org.apache.olingo.server.api.processor.PrimitiveCollectionProcessor;
import org.apache.olingo.server.api.processor.PrimitiveValueProcessor;
import org.apache.olingo.server.api.uri.UriInfo;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.processor.JPAActionRequestProcessor;
import com.sap.olingo.jpa.processor.core.processor.JPACUDRequestProcessor;
import com.sap.olingo.jpa.processor.core.processor.JPAProcessorFactory;
import com.sap.olingo.jpa.processor.core.processor.JPARequestProcessor;
public final class JPAODataRequestProcessor
implements PrimitiveValueProcessor, PrimitiveCollectionProcessor, ComplexProcessor, ComplexCollectionProcessor,
CountEntityCollectionProcessor, EntityProcessor, MediaEntityProcessor, ActionPrimitiveProcessor,
ActionVoidProcessor, CountComplexCollectionProcessor, CountPrimitiveCollectionProcessor {
private final JPAODataSessionContextAccess sessionContext;
private final JPAODataRequestContextAccess requestContext;
private JPAProcessorFactory factory;
public JPAODataRequestProcessor(final JPAODataSessionContextAccess sessionContext,
final JPAODataRequestContextAccess requestContext) {
super();
this.sessionContext = sessionContext;
this.requestContext = requestContext;
}
@Override
public void init(final OData odata, final ServiceMetadata serviceMetadata) {
this.factory = new JPAProcessorFactory(odata, serviceMetadata, sessionContext);
}
@Override
public void countEntityCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
performCountRequest(request, response, uriInfo);
}
@Override
public void countComplexCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
performCountRequest(request, response, uriInfo);
}
@Override
public void countPrimitiveCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
performCountRequest(request, response, uriInfo);
}
@Override
public void createEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat) throws ODataApplicationException,
ODataLibraryException {
try {
final JPACUDRequestProcessor processor = factory.createCUDRequestProcessor(uriInfo, responseFormat,
requestContext,
request.getAllHeaders());
processor.createEntity(request, response, requestFormat, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void createMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_CREATE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void deleteComplex(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
// Set NULL: .../Organizations('4')/Address
performClearFieldsRequest(request, response, uriInfo);
}
@Override
public void deleteEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
try {
final JPACUDRequestProcessor processor = this.factory.createCUDRequestProcessor(uriInfo, requestContext, request
.getAllHeaders());
processor.deleteEntity(request, response);
} catch (ODataApplicationException | ODataLibraryException e) {
if (e.getCause() instanceof final RollbackException rollback)
handleRollbackException(rollback);
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void deletePrimitive(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
// Set NULL: .../Organizations('4')/Address/Country
// https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752306
// 11.4.9.2 Set a Value to Null:
// A successful DELETE request to the edit URL for a structural property, or to the edit URL of the raw value of a
// primitive property, sets the property to null. The request body is ignored and should be empty. A DELETE request
// to a non-nullable value MUST fail and the service respond with 400 Bad Request or other appropriate error. The
// same rules apply whether the target is the value of a regular property or the value of a dynamic property. A
// missing dynamic property is defined to be the same as a dynamic property with value null. All dynamic properties
// are nullable.On success, the service MUST respond with 204 No Content and an empty body.
//
// Nullable checked by Olingo Core
performClearFieldsRequest(request, response, uriInfo);
}
@Override
public void deletePrimitiveValue(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
// .../Organizations('4')/Address/Country/$value
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE_VALUE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void deleteMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
// Set NULL: ../$value
// https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752305
// 11.4.8.2 Deleting Stream Values:
// A successful DELETE request to the edit URL of a stream property
// attempts to set the property to null and results
// in an error if the property is non-nullable. Attempting to request a
// stream property whose value is null results
// in 204 No Content.
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void readComplex(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readComplexCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readEntityCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readPrimitiveCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readPrimitive(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readPrimitiveValue(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void readMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, responseFormat, request.getAllHeaders(),
requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
requestContext.getDebugger().debug(this, e.getMessage());
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void updateComplex(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
// ../Organizations('5')/Address
// Not supported yet, as PATCH and PUT are allowed here
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_UPDATE_VALUE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void updateEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
try {
final JPACUDRequestProcessor processor = factory.createCUDRequestProcessor(uriInfo, responseFormat,
requestContext,
request.getAllHeaders());
processor.updateEntity(request, response, requestFormat, responseFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
if (e.getCause() instanceof final RollbackException rollback)
handleRollbackException(rollback);
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
private void handleRollbackException(final RollbackException exception) throws ODataJPAProcessorException {
if (exception.getCause() instanceof OptimisticLockException) {
throw new ODataJPAProcessorException(exception.getCause().getCause(), HttpStatusCode.PRECONDITION_FAILED);
}
throw new ODataJPAProcessorException(exception, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
@Override
public void updatePrimitive(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
// http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752306
// only PUT ../Organizations('5')/Address/StreetName
updateEntity(request, response, uriInfo, requestFormat, responseFormat);
}
@Override
public void updatePrimitiveValue(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
// ../Organizations('5')/Address/StreetName/$value
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_UPDATE_VALUE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void updateMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_UPDATE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void updatePrimitiveCollection(final ODataRequest request, final ODataResponse response,
final UriInfo uriInfo, final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
updateEntity(request, response, uriInfo, requestFormat, responseFormat);
}
@Override
public void deletePrimitiveCollection(final ODataRequest request, final ODataResponse response,
final UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException {
// Set NULL: .../Organizations('4')/Comment
// See deletePrimitive
performClearFieldsRequest(request, response, uriInfo);
}
@Override
public void updateComplexCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
updateEntity(request, response, uriInfo, requestFormat, responseFormat);
}
@Override
public void deleteComplexCollection(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException {
// Set NULL: .../Persons('4')/InhouseAddress
// See deletePrimitive
performClearFieldsRequest(request, response, uriInfo);
}
@Override
public void processActionPrimitive(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat, final ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
try {
final JPAActionRequestProcessor processor = this.factory.createActionProcessor(uriInfo, responseFormat, request
.getAllHeaders(), requestContext);
processor.performAction(request, response, requestFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
@Override
public void processActionVoid(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestFormat) throws ODataApplicationException, ODataLibraryException {
try {
final JPAActionRequestProcessor processor = this.factory.createActionProcessor(uriInfo, null, request
.getAllHeaders(), requestContext);
processor.performAction(request, response, requestFormat);
} catch (ODataApplicationException | ODataLibraryException e) {
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
private void performCountRequest(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo)
throws ODataApplicationException {
try {
final JPARequestProcessor processor = factory.createProcessor(uriInfo, ContentType.TEXT_PLAIN, request
.getAllHeaders(), requestContext, new JPAODataPathInformation(request));
processor.retrieveData(request, response, ContentType.TEXT_PLAIN);
} catch (final ODataApplicationException e) {
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, e);
}
}
private void performClearFieldsRequest(final ODataRequest request, final ODataResponse response,
final UriInfo uriInfo)
throws ODataApplicationException, ODataLibraryException { // NOSONAR
try {
final JPACUDRequestProcessor processor = factory.createCUDRequestProcessor(uriInfo, requestContext, request
.getAllHeaders());
processor.clearFields(request, response);
} catch (ODataApplicationException | ODataLibraryException e) {
if (e.getCause() instanceof final RollbackException rollback)
handleRollbackException(rollback);
throw e;
} catch (final ODataException e) {
throw new ODataApplicationException(e.getLocalizedMessage(),
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), null, 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/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataGroupsProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataGroupsProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class JPAODataGroupsProvider implements JPAODataGroupProvider {
private final List<String> groups = new ArrayList<>(0);
@Override
public List<String> getGroups() {
return groups;
}
/**
* Adds a single group. Null values are ignored.
* @param group
*/
public void addGroup(final String group) {
if (group != null)
groups.add(group);
}
/**
* Adds an array of groups
* @param groups
*/
public void addGroups(final String... groups) {
for (final String group : groups)
addGroup(group);
}
public void addGroups(final Collection<String> groups) {
for (final String group : groups)
addGroup(group);
}
@Override
public String toString() {
return "JPAODataGroupsProvider [groups=" + groups + "]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPADefaultErrorProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPADefaultErrorProcessor.java | package com.sap.olingo.jpa.processor.core.api;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ODataServerError;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.processor.DefaultProcessor;
import org.apache.olingo.server.api.processor.ErrorProcessor;
public final class JPADefaultErrorProcessor implements ErrorProcessor {
private final ErrorProcessor defaultProcessor;
JPADefaultErrorProcessor() {
super();
defaultProcessor = new DefaultProcessor();
}
@Override
public void init(OData odata, ServiceMetadata serviceMetadata) {
defaultProcessor.init(odata, serviceMetadata);
}
@Override
public void processError(ODataRequest request, ODataResponse response, ODataServerError serverError,
ContentType responseFormat) {
defaultProcessor.processError(request, response, serverError, responseFormat);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataExpandPage.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataExpandPage.java | package com.sap.olingo.jpa.processor.core.api;
import org.apache.olingo.server.api.uri.UriInfoResource;
public record JPAODataExpandPage(UriInfoResource uriInfo, int skip, int top, JPAODataSkipTokenProvider skipToken) {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAErrorProcessorWrapper.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAErrorProcessorWrapper.java | package com.sap.olingo.jpa.processor.core.api;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ODataServerError;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.processor.DefaultProcessor;
import org.apache.olingo.server.api.processor.ErrorProcessor;
public class JPAErrorProcessorWrapper implements ErrorProcessor {
private final ErrorProcessor defaultProcessor;
private final JPAErrorProcessor errorProcessor;
public JPAErrorProcessorWrapper(final JPAErrorProcessor errorProcessor) {
super();
this.defaultProcessor = new DefaultProcessor();
this.errorProcessor = errorProcessor;
}
@Override
public void init(OData odata, ServiceMetadata serviceMetadata) {
defaultProcessor.init(odata, serviceMetadata);
}
@Override
public void processError(ODataRequest request, ODataResponse response, ODataServerError serverError,
ContentType responseFormat) {
errorProcessor.processError(request, serverError);
defaultProcessor.processError(request, response, serverError, responseFormat);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataDatabaseProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataDatabaseProcessor.java | package com.sap.olingo.jpa.processor.core.api;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseSearch;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseTableFunction;
/**
* Interface is in a beta state
* @author Oliver Grande
*
*/
public interface JPAODataDatabaseProcessor extends JPAODataDatabaseSearch, JPAODataDatabaseTableFunction {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataTransactionFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataTransactionFactory.java | package com.sap.olingo.jpa.processor.core.api;
import jakarta.persistence.RollbackException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPATransactionException;
/**
* A wrapper to abstract from various transaction APIs provided by JAVA or e.g. Spring like
* javax.persistence.EntityTransaction, javax.transaction.UserTransaction, javax.transaction.Transaction or
* org.springframework.transaction.jta.JtaTransactionManager.
* </p>
*
* JPA Processor needs to be able to create transactions to be able to handle <a
* href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752316">Change
* Sets</a> correctly. Each Change Set has to be processed in an own transaction. Please not that the batch processor
* will create a response with http status code <i>501 Not Implemented</i> in case he cannot create a transaction.
* <p>
*
* In case not TransactionFactory is provided the JPA Processor will create an instance of
* {@link JPAODataDefaultTransactionFactory}, which shall be sufficient for most uses cases.
*
* @author Oliver Grande
* Created: 07.10.2019
*
*/
public interface JPAODataTransactionFactory {
/**
*
* @return a new transaction
*/
JPAODataTransaction createTransaction() throws ODataJPATransactionException;
boolean hasActiveTransaction();
public static interface JPAODataTransaction {
/**
*
* @throws ODataJPATransactionException
* @throws RollbackException
*/
public void commit() throws ODataJPATransactionException, RollbackException; // NOSONAR
public void rollback() throws ODataJPATransactionException;
public boolean isActive() throws ODataJPATransactionException;
public boolean rollbackOnly() throws ODataJPATransactionException;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataGroupProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataGroupProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
/**
* Container that provides field groups
* @author Oliver Grande
* Created: 30.06.2019
*
*/
public interface JPAODataGroupProvider {
/**
* Provides a list of all field groups to be taken into account
* @return
*/
public List<String> getGroups();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPADefaultPagingProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPADefaultPagingProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.Optional;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.uri.UriInfo;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import com.sap.olingo.jpa.processor.core.query.JPACountQuery;
class JPADefaultPagingProvider implements JPAODataPagingProvider {
@Override
public Optional<JPAODataPage> getNextPage(final String skipToken, final OData odata,
final ServiceMetadata serviceMetadata, final JPARequestParameterMap requestParameter, final EntityManager em) {
return Optional.empty();
}
@Override
public Optional<JPAODataPage> getFirstPage(final JPARequestParameterMap requestParameter,
final JPAODataPathInformation pathInformation, final UriInfo uriInfo, final Integer preferredPageSize,
final JPACountQuery countQuery, final EntityManager em) throws ODataApplicationException {
final var skipValue = uriInfo.getSkipOption() != null ? determineSkipValue(uriInfo) : 0;
final var topValue = uriInfo.getTopOption() != null ? determineTopValue(uriInfo) : Integer.MAX_VALUE;
return Optional.of(new JPAODataPage(uriInfo, skipValue, topValue, null));
}
private int determineTopValue(final UriInfo uriInfo) throws ODataJPAQueryException {
final var value = uriInfo.getTopOption().getValue();
if (value < 0)
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_INVALID_VALUE,
HttpStatusCode.BAD_REQUEST, Integer.toString(value), "$skip");
return value;
}
private int determineSkipValue(final UriInfo uriInfo) throws ODataJPAQueryException {
final var value = uriInfo.getSkipOption().getValue();
if (value < 0)
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_INVALID_VALUE,
HttpStatusCode.BAD_REQUEST, Integer.toString(value), "$skip");
return value;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataSessionContextAccess.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataSessionContextAccess.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
import java.util.Optional;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.apache.olingo.server.api.processor.ErrorProcessor;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.processor.cb.ProcessorSqlPatternProvider;
import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations;
/**
*
* @author Oliver Grande
*
*/
public interface JPAODataSessionContextAccess {
public JPAODataDatabaseProcessor getDatabaseProcessor();
public JPAODataDatabaseOperations getOperationConverter();
public List<EdmxReference> getReferences();
/**
* Returns a list of packages that may contain Enumerations of Java implemented OData operations
* @deprecated (method won't return correct value in case of multiple versions, use getApiVersion)
*/
@Deprecated(since = "2.2.3", forRemoval = true)
public default List<String> getPackageName() {
return List.of();
}
/**
* If server side paging shall be supported <code>getPagingProvider</code> returns an implementation of a paging
* provider. Details about the OData specification can be found under <a
* href=
* "https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Server-Driven_Paging">OData
* Version 4.0 Part 1 - 11.2.5.7 Server-Driven Paging</a>
* @return
*/
public JPAODataPagingProvider getPagingProvider();
/**
* @deprecated (method won't return correct value in case of multiple versions, use getApiVersion)
*/
@Deprecated(since = "2.2.3", forRemoval = true)
public default Optional<? extends EntityManagerFactory> getEntityManagerFactory() {
return Optional.empty();
}
public default ErrorProcessor getErrorProcessor() {
return null;
}
/**
* @deprecated (method won't return correct value in case of multiple versions, use getApiVersion)
*/
@Deprecated(since = "2.2.3", forRemoval = true)
public default String getMappingPath() {
return "";
}
public default <T extends JPAODataBatchProcessor> JPAODataBatchProcessorFactory<T> getBatchProcessorFactory() {
return null;
}
public default boolean useAbsoluteContextURL() {
return false;
}
public List<AnnotationProvider> getAnnotationProvider();
public JPAODataQueryDirectives getQueryDirectives();
public ProcessorSqlPatternProvider getSqlPatternProvider();
public JPAODataApiVersionAccess getApiVersion(String id);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataCRUDRequestContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataCRUDRequestContext.java | package com.sap.olingo.jpa.processor.core.api;
import javax.annotation.Nonnull;
public interface JPAODataCRUDRequestContext extends JPAODataRequestContext {
public void setCUDRequestHandler(@Nonnull final JPACUDRequestHandler jpaCUDRequestHandler);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataServiceDocumentProcessor.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataServiceDocumentProcessor.java | package com.sap.olingo.jpa.processor.core.api;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.etag.ETagHelper;
import org.apache.olingo.server.api.etag.ServiceMetadataETagSupport;
import org.apache.olingo.server.api.processor.DefaultProcessor;
import org.apache.olingo.server.api.processor.ServiceDocumentProcessor;
import org.apache.olingo.server.api.serializer.ODataSerializer;
import org.apache.olingo.server.api.uri.UriInfo;
public class JPAODataServiceDocumentProcessor implements ServiceDocumentProcessor {
private OData odata;
private ServiceMetadata serviceMetadata;
private final JPAODataSessionContextAccess serviceContext;
public JPAODataServiceDocumentProcessor(final JPAODataSessionContextAccess serviceContext) {
super();
this.serviceContext = serviceContext;
}
@Override
public void init(OData odata, ServiceMetadata serviceMetadata) {
this.odata = odata;
this.serviceMetadata = serviceMetadata;
}
/**
* This is a copy from @see
* {@link DefaultProcessor#readServiceDocument(ODataRequest, ODataResponse, UriInfo, ContentType)}
*
*/
@Override
public void readServiceDocument(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
final ContentType requestedContentType) throws ODataApplicationException, ODataLibraryException {
String uri = serviceContext.useAbsoluteContextURL() ? request.getRawBaseUri() : null;
boolean isNotModified = false;
ServiceMetadataETagSupport eTagSupport = serviceMetadata.getServiceMetadataETagSupport();
if (eTagSupport != null && eTagSupport.getServiceDocumentETag() != null) {
// Set application etag at response
response.setHeader(HttpHeader.ETAG, eTagSupport.getServiceDocumentETag());
// Check if service document has been modified
ETagHelper eTagHelper = odata.createETagHelper();
isNotModified = eTagHelper.checkReadPreconditions(eTagSupport.getServiceDocumentETag(), request
.getHeaders(HttpHeader.IF_MATCH), request.getHeaders(HttpHeader.IF_NONE_MATCH));
}
// Send the correct response
if (isNotModified) {
response.setStatusCode(HttpStatusCode.NOT_MODIFIED.getStatusCode());
} else {
// HTTP HEAD requires no payload but a 200 OK response
if (HttpMethod.HEAD == request.getMethod()) {
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
} else {
ODataSerializer serializer = odata.createSerializer(requestedContentType);
response.setContent(serializer.serviceDocument(serviceMetadata, uri).getContent());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, requestedContentType.toContentTypeString());
}
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataApiVersionAccess.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataApiVersionAccess.java | package com.sap.olingo.jpa.processor.core.api;
import jakarta.persistence.EntityManagerFactory;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
public interface JPAODataApiVersionAccess {
public final String DEFAULT_VERSION = "DEFAULT";
String getId();
JPAEdmProvider getEdmProvider();
EntityManagerFactory getEntityManagerFactory();
String getMappingPath();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAAbstractCUDRequestHandler.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAAbstractCUDRequestHandler.java | package com.sap.olingo.jpa.processor.core.api;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult;
import com.sap.olingo.jpa.processor.core.processor.JPARequestEntity;
public abstract class JPAAbstractCUDRequestHandler implements JPACUDRequestHandler {
@Override
public void deleteEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public Object createEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_CREATE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em,
final HttpMethod httpMethod) throws ODataJPAProcessException {
throw new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_UPDATE,
HttpStatusCode.NOT_IMPLEMENTED);
}
@Override
public void validateChanges(final EntityManager em) throws ODataJPAProcessException {
// Do nothing. If needed override method.
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorFactory.java | package com.sap.olingo.jpa.processor.core.api;
import javax.annotation.Nonnull;
public interface JPAODataBatchProcessorFactory<T extends JPAODataBatchProcessor> {
T getBatchProcessor(@Nonnull final JPAODataSessionContextAccess serviceContext,
@Nonnull final JPAODataRequestContextAccess requestContext);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPagingProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPagingProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import com.sap.olingo.jpa.processor.core.query.JPACountQuery;
import com.sap.olingo.jpa.processor.core.query.JPAExpandCountQuery;
/**
* Supporting
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752288">
* Server Drive Paging (Part1 11.2.5.7)</a>
* @author Oliver Grande
*
*/
public interface JPAODataPagingProvider {
/**
* Returns the page related to a given skiptoken.
* If the skiptoken is not known the method must return null.
* @param skipToken
* @return Next page. If the page is null, an exception
* @deprecated implement
* {@link #getNextPage(String, OData, ServiceMetadata, JPARequestParameterMap, EntityManager)}
* instead
*/
@Deprecated(since = "2.1.0", forRemoval = true)
default JPAODataPage getNextPage(@Nonnull final String skipToken) {
return getNextPage(skipToken, null, null, null, null).orElse(null);
}
/**
* Returns the page related to a given skiptoken.
* If the skiptoken is not known the method must return an empty optional.
* @param skipToken
* @param odata
* @param serviceMetadata
* @param requestParameter
* @return
*/
default Optional<JPAODataPage> getNextPage(@Nonnull final String skipToken, final OData odata,
final ServiceMetadata serviceMetadata, final JPARequestParameterMap requestParameter, final EntityManager em) {
return Optional.ofNullable(getNextPage(skipToken)); // NOSONAR
}
/**
* Based on the query the provider decides if a paging is required and return the first page.
* @param uriInfo
* @param preferredPageSize Value from odata.maxpagesize preference header
* @param countQuery A query that can be used to determine the maximum number of results that can be expected. Only if
* the number of expected results is bigger then the page size a next link
* @param em
* @return
* @throws ODataApplicationException
* @deprecated implement
* {@link #getFirstPage(JPARequestParameterMap, JPAODataPathInformation, UriInfo, Integer, JPACountQuery, EntityManager)}
* instead *
*/
@Deprecated(since = "2.1.0", forRemoval = true)
default JPAODataPage getFirstPage(final UriInfo uriInfo, @Nullable final Integer preferredPageSize,
final JPACountQuery countQuery, final EntityManager em) throws ODataApplicationException {
return getFirstPage(null, null, uriInfo, preferredPageSize, countQuery, em).orElse(null);
}
/**
* Based on the query the provider decides if a paging is required and return the first page.
* @param requestParameter The parameter from the request context
* @param pathInformation Request URI split info different segments like it is expected by the Olingo URI parser
* @param uriInfo
* @param preferredPageSize Value of the odata.maxpagesize preference header
* @param countQuery A query that can be used to determine the maximum number of results that can be
* expected. Only if the number of expected results is bigger then the page size a next link
* @param em An instance of the entity manager
* @return An optional of the page that shall be read. In case the optional is empty, all records are read from the
* database.
* @throws ODataApplicationException
*/
default Optional<JPAODataPage> getFirstPage(final JPARequestParameterMap requestParameter,
final JPAODataPathInformation pathInformation, final UriInfo uriInfo, @Nullable final Integer preferredPageSize,
final JPACountQuery countQuery, final EntityManager em) throws ODataApplicationException {
return Optional.ofNullable(getFirstPage(uriInfo, preferredPageSize, countQuery, em));// NOSONAR
}
/**
* Requires module {@code odata-jpa-processor-cb}
* @param requestParameter The parameter from the request context
* @param pathInformation
* @param uriInfo
* @param association
* @param preferredPageSize
* @param count
* @param em An instance of the entity manager
* @return
*/
default Optional<JPAODataExpandPage> getFirstPageExpand(final JPARequestParameterMap requestParameter,
final JPAODataPathInformation pathInformation, final UriInfoResource uriInfo, final TopOption top,
final SkipOption skip, final JPAAssociationAttribute association, final JPAExpandCountQuery count,
final EntityManager em) throws ODataApplicationException {
return Optional.empty();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPageExpandInfo.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPageExpandInfo.java | package com.sap.olingo.jpa.processor.core.api;
/**
*
* @param navigationPropertyPath Concatenated path information leading to the next expand
* @param keyPath Concatenated key information to be used to convert the expand
*
* @author Oliver Grande
* @since 2.2.0
*
*/
public record JPAODataPageExpandInfo(String navigationPropertyPath, String keyPath) {
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPACUDRequestHandler.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPACUDRequestHandler.java | package com.sap.olingo.jpa.processor.core.api;
import jakarta.persistence.EntityManager;
import org.apache.olingo.commons.api.http.HttpMethod;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult;
import com.sap.olingo.jpa.processor.core.processor.JPARequestEntity;
public interface JPACUDRequestHandler {
/**
*
* @param requestEntity
* @param em
* @throws ODataJPAProcessException
*/
public void deleteEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException;
/**
* Hook to create an entity. Transaction handling is done outside to guarantee transactional behavior of change
* sets in batch requests. This method has to return the newly create entity even so validateChanges is implemented.
* @param requestEntity
* @param em
* @return The newly created instance or map of created attributes including default and added values
* following the same rules as jpaAttributes
* @throws ODataJPAProcessException
*/
public Object createEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException;
/**
* Hook to handle all request that change an existing entity.
* This includes update and upsert on entities, updates on properties and values, updates on relations as well as
* deletions on values and properties. <br>
* <b>Note:</b> Deviating from the OData standard changes on collection properties will be provided as PATCH, as it is
* from an entity point of view is the partial change. An
* implementation needs to take care that all elements of the collection are exchanged!
* </p>
* @see
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752300"
* >OData Version 4.0 Part 1 - 11.4.3 Update an Entity</a><br>
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752301"
* >OData Version 4.0 Part 1 - 11.4.4 Upsert an Entity</a><br>
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752303"
* >OData Version 4.0 Part 1 - 11.4.6 Modifying Relationships between Entities</a><br>
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part1-protocol/odata-v4.0-errata03-os-part1-protocol-complete.html#_Toc453752306"
* >OData Version 4.0 Part 1 - 11.4.9 Managing Values and Properties Directly</a><br>
*
* @param requestEntity See {@link com.sap.olingo.jpa.processor.core.processor.JPARequestEntity JPARequestEntity}
* @param em Instance of an entity manager with an open transaction.
* @param httpMethod The original http method: PATCH, PUT, DELETE
* @return The response describes the performed changes (Created or Updated) as well as the result of the operation.
* It must not be null. Even if nothing was changed => update is idempotent
* @throws ODataJPAProcessException
*/
public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em,
final HttpMethod httpMethod) throws ODataJPAProcessException;
/**
* Hook that is called after all changes of one transaction have been processed. The method shall enable a check of
* all modification within the new context. This can be imported if multiple entities are changes with the same
* request (batch request or deep-insert) and consistency constrains exist between them.
* <p>
* In case changes are made to the entities, these changes are not part of the response in case of batch requests.
* @throws ODataJPAProcessException
*/
public void validateChanges(final EntityManager em) throws ODataJPAProcessException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataEtagHelper.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataEtagHelper.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.Collection;
import javax.annotation.Nonnull;
import org.apache.olingo.server.api.etag.PreconditionException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAQueryException;
public interface JPAODataEtagHelper {
/**
* <p>
* Checks the preconditions of a read request with a given ETag value
* against the If-Match and If-None-Match HTTP headers.
* </p>
* <p>
* If the given ETag value is not matched by the ETag information in the If-Match headers,
* and there are ETags in the headers to be matched, a "Precondition Failed" exception is
* thrown.
* </p>
* <p>
* If the given ETag value is matched by the ETag information in the If-None-Match headers,
* <code>true</code> is returned, and applications are supposed to return an empty response
* with a "Not Modified" status code and the ETag header, <code>false</code> otherwise.
* </p>
* <p>
* All matching uses weak comparison as described in
* <a href="https://www.ietf.org/rfc/rfc7232.txt">RFC 7232</a>, section 2.3.2.
* </p>
* <p>
* This method does not nothing and returns <code>false</code> if the ETag value is
* <code>null</code>.
* </p>
* @param eTag the ETag value to match
* @param ifMatchHeaders the If-Match header values
* @param ifNoneMatchHeaders the If-None-Match header values
* @return whether a "Not Modified" response should be used
*/
public boolean checkReadPreconditions(String etag,
Collection<String> ifMatchHeaders, Collection<String> ifNoneMatchHeaders)
throws PreconditionException;
/**
* <p>
* Checks the preconditions of a change request (with HTTP methods PUT, PATCH, or DELETE)
* with a given ETag value against the If-Match and If-None-Match HTTP headers.
* </p>
* <p>
* If the given ETag value is not matched by the ETag information in the If-Match headers,
* and there are ETags in the headers to be matched, or
* if the given ETag value is matched by the ETag information in the If-None-Match headers,
* a "Precondition Failed" exception is thrown.
* </p>
* <p>
* All matching uses weak comparison as described in
* <a href="https://www.ietf.org/rfc/rfc7232.txt">RFC 7232</a>, section 2.3.2.
* </p>
* <p>
* This method does not nothing if the ETag value is <code>null</code>.
* </p>
* @param eTag the ETag value to match
* @param ifMatchHeaders the If-Match header values
* @param ifNoneMatchHeaders the If-None-Match header values
*/
public void checkChangePreconditions(String etag,
Collection<String> ifMatchHeaders, Collection<String> ifNoneMatchHeaders)
throws PreconditionException;
/**
* Converts the value of an ETag into a the corresponding string. <br>
* A value is converted by calling the toString method with one exception. In case
* the value is an instance of type {@link java.sql.Timestamp}, the time stamp is first converted into
* a {@link java.time.Instant} to get a <a href="https://www.ietf.org/rfc/rfc7232.txt">RFC 7232</a> compliant string.
*
* @param entityType the ETag belongs to
* @param value raw value of the ETag
* @return ETag string. It is empty if the value is null and null if the entity type has no ETag property
* @throws ODataJPAQueryException
*/
public String asEtag(@Nonnull final JPAEntityType entityType, final Object value) throws ODataJPAQueryException;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPathInformation.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPathInformation.java | package com.sap.olingo.jpa.processor.core.api;
import java.io.Serializable;
import javax.annotation.Nullable;
import org.apache.olingo.server.api.ODataRequest;
public record JPAODataPathInformation(String baseUri, String oDataPath, @Nullable String queryPath,
@Nullable String fragments) implements Serializable {
public JPAODataPathInformation(final ODataRequest request) {
this(request.getRawBaseUri(), request.getRawODataPath(), request.getRawQueryPath(), null);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
/**
* Container that provides claims
*
* @author Oliver Grande
* Created: 30.06.2019
*
*/
public interface JPAODataClaimProvider {
/**
* @param attributeName
* @return Provides a list claim values for a given attribute.
*/
@Nonnull
List<JPAClaimsPair<?>> get(final String attributeName); // NOSONAR
/**
*
* @return An optional that may contain the user id for the current request
*/
default Optional<String> user() {
return Optional.empty();
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataQueryDirectives.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataQueryDirectives.java | package com.sap.olingo.jpa.processor.core.api;
import com.sap.olingo.jpa.processor.core.api.JPAODataServiceContext.Builder;
public sealed interface JPAODataQueryDirectives {
public static JPAODataQueryDirectivesBuilder with(final Builder builder) {
return new JPAODataQueryDirectivesBuilderImpl(builder);
}
int getMaxValuesInInClause();
UuidSortOrder getUuidSortOrder();
static record JPAODataQueryDirectivesImpl(int maxValuesInInClause, UuidSortOrder uuidSortOrder) implements
JPAODataQueryDirectives {
@Override
public int getMaxValuesInInClause() {
return maxValuesInInClause;
}
@Override
public UuidSortOrder getUuidSortOrder() {
return uuidSortOrder;
}
}
static class JPAODataQueryDirectivesBuilderImpl implements JPAODataQueryDirectivesBuilder {
private final Builder parent;
private int maxValuesInInClause = 0;
private UuidSortOrder uuidSortOrder = UuidSortOrder.AS_STRING;
JPAODataQueryDirectivesBuilderImpl(final Builder builder) {
this.parent = builder;
}
@Override
public JPAODataQueryDirectivesBuilder maxValuesInInClause(final int maxValues) {
this.maxValuesInInClause = maxValues;
return this;
}
@Override
public JPAODataServiceContextBuilder build() {
return parent.setQueryDirectives(new JPAODataQueryDirectivesImpl(maxValuesInInClause, uuidSortOrder));
}
@Override
public JPAODataQueryDirectivesBuilder uuidSortOrder(final UuidSortOrder order) {
this.uuidSortOrder = order;
return this;
}
}
public enum UuidSortOrder {
AS_STRING,
AS_BYTE_ARRAY,
AS_JAVA_UUID;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestHandler.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataRequestHandler.java | package com.sap.olingo.jpa.processor.core.api;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHttpHandler;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
public class JPAODataRequestHandler {
private static final String REQUEST_MAPPING_ATTRIBUTE = "requestMapping";
private final JPAODataServiceContext serviceContext;
private final JPAODataInternalRequestContext requestContext;
final OData odata;
/**
* Create a handler without special request context. Default implementations are used if present.
* @param serviceContext
*/
public JPAODataRequestHandler(final JPAODataSessionContextAccess serviceContext) {
this(serviceContext, OData.newInstance());
}
/**
*
* @param serviceContext
* @param requestContext
*/
public JPAODataRequestHandler(final JPAODataSessionContextAccess serviceContext,
final JPAODataRequestContext requestContext) {
this(serviceContext, requestContext, OData.newInstance());
}
/**
* Give the option to inject the odata helper e.g. for testing
* @param serviceContext
* @param odata
*/
JPAODataRequestHandler(final JPAODataSessionContextAccess serviceContext, final OData odata) {
this(serviceContext, JPAODataRequestContext.with().build(), odata);
}
JPAODataRequestHandler(final JPAODataSessionContextAccess serviceContext, final JPAODataRequestContext requestContext,
final OData odata) {
this.serviceContext = (JPAODataServiceContext) serviceContext;
this.requestContext = new JPAODataInternalRequestContext(requestContext, serviceContext, odata);
this.odata = odata;
}
public void process(final HttpServletRequest request, final HttpServletResponse response) throws ODataException {
processInternal(request, response);
}
private void processInternal(final HttpServletRequest request, final HttpServletResponse response)
throws ODataException {
final JPAEdmProvider jpaEdm = requestContext.getEdmProvider();
final ODataHttpHandler handler = odata.createHandler(odata.createServiceMetadata(jpaEdm, jpaEdm.getReferences()));
jpaEdm.setRequestLocales(request.getLocales());
final HttpServletRequest mappedRequest = prepareRequestMapping(request, requestContext.getMappingPath());
handler.register(requestContext.getDebugSupport());
handler.register(new JPAODataRequestProcessor(serviceContext, requestContext));
handler.register(serviceContext.getBatchProcessorFactory().getBatchProcessor(serviceContext, requestContext));
handler.register(jpaEdm.getServiceDocument());
handler.register(serviceContext.getErrorProcessor());
handler.register(new JPAODataServiceDocumentProcessor(serviceContext));
handler.process(mappedRequest, response);
}
private HttpServletRequest prepareRequestMapping(final HttpServletRequest request, final String requestPath) {
if (requestPath != null && !requestPath.isEmpty()) {
final HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request);
wrappedRequest.setAttribute(REQUEST_MAPPING_ATTRIBUTE, requestPath);
return wrappedRequest;
} else {
return request;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataExternalRequestContext.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataExternalRequestContext.java | package com.sap.olingo.jpa.processor.core.api;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
import org.apache.olingo.server.api.debug.DebugSupport;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.processor.core.processor.JPARequestParameterHashMap;
public class JPAODataExternalRequestContext implements JPAODataRequestContext {
private final JPARequestParameterMap customParameter;
private final DebugSupport debugSupport;
private final Optional<JPAODataClaimProvider> claims;
private final Optional<JPAODataGroupProvider> groups;
private final JPAODataTransactionFactory transactionFactory;
private final EntityManager em;
private final JPACUDRequestHandler cudRequestHandler;
private final List<Locale> locales;
private final String version;
public JPAODataExternalRequestContext(final Builder builder) {
this.debugSupport = builder.debugSupport;
this.claims = Optional.ofNullable(builder.claimsProvider);
this.groups = Optional.ofNullable(builder.groupsProvider);
this.transactionFactory = builder.transactionFactory;
this.em = builder.em;
this.cudRequestHandler = builder.cudRequestHandler;
this.customParameter = builder.customParameter;
this.locales = builder.locales;
this.version = builder.version;
}
@Override
public EntityManager getEntityManager() {
return em;
}
@Override
public Optional<JPAODataClaimProvider> getClaimsProvider() {
return claims;
}
@Override
public Optional<JPAODataGroupProvider> getGroupsProvider() {
return groups;
}
@Override
public JPACUDRequestHandler getCUDRequestHandler() {
return cudRequestHandler;
}
@Override
public DebugSupport getDebuggerSupport() {
return debugSupport;
}
@Override
public JPAODataTransactionFactory getTransactionFactory() {
return transactionFactory;
}
@Override
public List<Locale> getLocales() {
return locales;
}
@Override
public JPARequestParameterMap getRequestParameter() {
return customParameter;
}
@Override
public String getVersion() {
return version;
}
public static class Builder {
public static final int CONTAINS_ONLY_LANGU = 1;
public static final int CONTAINS_LANGU_COUNTRY = 2;
public static final String SELECT_ITEM_SEPARATOR = ",";
private final JPARequestParameterMap customParameter = new JPARequestParameterHashMap();
private DebugSupport debugSupport;
private JPAODataClaimProvider claimsProvider;
private JPAODataGroupProvider groupsProvider;
private JPAODataTransactionFactory transactionFactory;
private EntityManager em;
private JPACUDRequestHandler cudRequestHandler;
private List<Locale> locales = emptyList();
private String version = JPAODataApiVersionAccess.DEFAULT_VERSION;
public JPAODataRequestContext build() {
return new JPAODataExternalRequestContext(this);
}
/**
* Adds a Claims Provider to the request context providing the claims of the current user.
* @param provider
* @return Builder
*/
public Builder setClaimsProvider(@Nullable final JPAODataClaimProvider provider) {
this.claimsProvider = provider;
return this;
}
/**
*
* @param cudRequestHandler
* @return Builder
*/
public Builder setCUDRequestHandler(@Nonnull final JPACUDRequestHandler cudRequestHandler) {
this.cudRequestHandler = requireNonNull(cudRequestHandler);
return this;
}
/**
* Add a request specific parameter to re request context.
* @param name
* @param value
* @return
*/
public Builder setParameter(@Nonnull final String name, @Nullable final Object value) {
customParameter.put(requireNonNull(name), value);
return this;
}
/**
*
* @param debugSupport
* @return Builder
*/
public Builder setDebugSupport(@Nullable final DebugSupport debugSupport) {
this.debugSupport = debugSupport;
return this;
}
/**
* An entity manager can be provided. If the entity manager is not provided, one is created automatically from the
* entity manager factory provided by the session context {@link JPAODataServiceContext}
* @param em
* @return Builder
*/
public Builder setEntityManager(@Nonnull final EntityManager em) {
this.em = requireNonNull(em);
return this;
}
/**
* Adds a Field Group Provider to the request context providing the field groups the current user is assigned to.
* @param provider
* @return Builder
*/
public Builder setGroupsProvider(@Nullable final JPAODataGroupProvider provider) {
this.groupsProvider = provider;
return this;
}
/**
* Sets a transaction factory. If non is provided {@link JPAODataDefaultTransactionFactory} is taken.
* @see JPAODataTransactionFactory
* @param transactionFactory
* @return Builder
*/
public Builder setTransactionFactory(@Nullable final JPAODataTransactionFactory transactionFactory) {
this.transactionFactory = transactionFactory;
return this;
}
/**
* Sets the locales relevant for the current request. The first locale is used e.g. for description properties. If
* no locale is set, as a fallback the accept-language header is used.
* @param locales
* @return
*/
public Builder setLocales(@Nonnull final List<Locale> locales) {
this.locales = requireNonNull(locales);
return this;
}
/**
* Sets the locale relevant for the current request. The locale is used e.g. for description properties. If no
* locale is set, as a fallback the accept-language header is used.
* @param locale
* @return
*/
public Builder setLocales(@Nonnull final Locale locale) {
this.locales = Collections.singletonList(requireNonNull(locale));
return this;
}
public Builder setVersion(final String version) {
this.version = version;
return this;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPage.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataPage.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.Collections;
import java.util.List;
import org.apache.olingo.server.api.uri.UriInfoResource;
/**
* A page in case a the amount of returned data shall be restricted by the server.
*
* @param uriInfo UriInfoResource of the original request
* @param skip Skip value to be used
* @param top Top value to be used
* @param skipToken The skip token to be used in the next link for non expand requests.
* @param expandInformation Provides for pages of restricted expand requests the path and key information needed to build the
* next
* request.
*
*/
public record JPAODataPage(UriInfoResource uriInfo, int skip, int top, Object skipToken,
List<JPAODataPageExpandInfo> expandInformation) {
public JPAODataPage(final UriInfoResource uriInfo, final int skip, final int top, final Object skipToken) {
this(uriInfo, skip, top, skipToken, Collections.emptyList());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Container that contains the claims that must be fulfilled, so an entity my be modified or read.
* @author Oliver Grande
*
*/
public class JPAODataClaimsProvider implements JPAODataClaimProvider {
private final Map<String, List<JPAClaimsPair<?>>> claims = new HashMap<>();
private final Optional<String> user;
public JPAODataClaimsProvider() {
this(null);
}
public JPAODataClaimsProvider(final String user) {
super();
this.user = Optional.ofNullable(user);
}
public void add(final String attributeName, final JPAClaimsPair<?> claimsPair) {
claims.computeIfAbsent(attributeName, k -> new ArrayList<>());
claims.get(attributeName).add(claimsPair);
}
@Override
public List<JPAClaimsPair<?>> get(final String attributeName) { // NOSONAR
if (!claims.containsKey(attributeName))
return Collections.emptyList();
return claims.get(attributeName);
}
@Override
public Optional<String> user() {
return user;
}
@Override
public String toString() {
return "JPAODataClaimsProvider [claims=" + claims + ", user=" + user + "]";
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPADefaultBatchProcessorFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPADefaultBatchProcessorFactory.java | package com.sap.olingo.jpa.processor.core.api;
public class JPADefaultBatchProcessorFactory implements JPAODataBatchProcessorFactory<JPAODataBatchProcessor> {
@Override
public JPAODataBatchProcessor getBatchProcessor(final JPAODataSessionContextAccess serviceContext,
final JPAODataRequestContextAccess requestContext) {
return new JPAODataBatchProcessor(serviceContext, requestContext);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAServiceDebugger.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAServiceDebugger.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
import org.apache.olingo.server.api.debug.RuntimeMeasurement;
public interface JPAServiceDebugger {
public List<RuntimeMeasurement> getRuntimeInformation();
public default void debug(final Object instance, final String pattern, final Object... arguments) {}
public default void trace(final Object instance, final String pattern, final Object... arguments) {}
public default void debug(final Object instance, final String log) {}
public JPARuntimeMeasurement newMeasurement(final Object instance, final String methodName);
public static interface JPARuntimeMeasurement extends AutoCloseable {
@Override
void close();
long getMemoryConsumption();
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataSkipTokenProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataSkipTokenProvider.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.List;
public interface JPAODataSkipTokenProvider {
String get(final List<JPAODataPageExpandInfo> foreignKeyStack);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataQueryDirectivesBuilder.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataQueryDirectivesBuilder.java | package com.sap.olingo.jpa.processor.core.api;
import com.sap.olingo.jpa.processor.core.api.JPAODataQueryDirectives.UuidSortOrder;
public interface JPAODataQueryDirectivesBuilder {
JPAODataQueryDirectivesBuilder maxValuesInInClause(int i);
JPAODataQueryDirectivesBuilder uuidSortOrder(UuidSortOrder order);
JPAODataServiceContextBuilder build();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataDefaultTransactionFactory.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataDefaultTransactionFactory.java | package com.sap.olingo.jpa.processor.core.api;
import java.util.Objects;
import javax.annotation.Nonnull;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.RollbackException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sap.olingo.jpa.processor.core.exception.ODataJPATransactionException;
public class JPAODataDefaultTransactionFactory implements JPAODataTransactionFactory {
private static final Log LOGGER = LogFactory.getLog(JPAODataDefaultTransactionFactory.class);
private final EntityManager em;
private JPAODataTransaction currentTransaction;
public JPAODataDefaultTransactionFactory(@Nonnull final EntityManager em) {
super();
this.em = Objects.requireNonNull(em);
}
@Override
public JPAODataTransaction createTransaction() throws ODataJPATransactionException {
try {
if (currentTransaction != null && currentTransaction.isActive())
throw new ODataJPATransactionException();
currentTransaction = new JPAODataEntityTransaction(em.getTransaction());
return currentTransaction;
} catch (final Exception e) {
throw new ODataJPATransactionException(e);
}
}
@Override
public boolean hasActiveTransaction() {
try {
final boolean baseActive = em.getTransaction().isActive();
if (currentTransaction == null && !baseActive)
return false;
else if (currentTransaction == null)
return true;
return currentTransaction.isActive();
} catch (RuntimeException | ODataJPATransactionException e) {
LOGGER.debug("Exception during hasActiveTransaction: " + e.getMessage());
return true;
}
}
private static class JPAODataEntityTransaction implements JPAODataTransaction {
private final EntityTransaction et;
public JPAODataEntityTransaction(final EntityTransaction et) {
super();
this.et = et;
this.et.begin();
}
@Override
public void commit() throws ODataJPATransactionException {
try {
et.commit();
} catch (final RollbackException e) {
throw e;
} catch (final RuntimeException e) {
throw new ODataJPATransactionException(e);
}
}
@Override
public void rollback() throws ODataJPATransactionException {
try {
et.rollback();
} catch (final RuntimeException e) {
throw new ODataJPATransactionException(e);
}
}
@Override
public boolean isActive() throws ODataJPATransactionException {
try {
return et.isActive();
} catch (final RuntimeException e) {
throw new ODataJPATransactionException(e);
}
}
@Override
public boolean rollbackOnly() throws ODataJPATransactionException {
try {
return et.getRollbackOnly();
} catch (final RuntimeException e) {
throw new ODataJPATransactionException(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/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExampleModifyException.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExampleModifyException.java | package com.sap.olingo.jpa.processor.core.api.example;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
public class JPAExampleModifyException extends ODataJPAProcessException { // NOSONAR
private static final long serialVersionUID = 121932494074522961L;
private static final String BUNDLE_NAME = "example-exceptions-i18n";
public enum MessageKeys implements ODataJPAMessageKey {
ENTITY_NOT_FOUND,
ENTITY_ALREADY_EXISTS,
MODIFY_NOT_ALLOWED,
WILDCARD_RANGE_NOT_SUPPORTED;
@Override
public String getKey() {
return name();
}
}
public JPAExampleModifyException(final MessageKeys messageKey, final HttpStatusCode statusCode) {
super(messageKey.getKey(), statusCode);
}
public JPAExampleModifyException(final Exception e, final HttpStatusCode statusCode) {
super(e, statusCode);
}
@Override
protected String getBundleName() {
return BUNDLE_NAME;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExampleCUDRequestHandler.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExampleCUDRequestHandler.java | package com.sap.olingo.jpa.processor.core.api.example;
import static com.sap.olingo.jpa.processor.core.api.example.JPAExampleModifyException.MessageKeys.ENTITY_ALREADY_EXISTS;
import static com.sap.olingo.jpa.processor.core.api.example.JPAExampleModifyException.MessageKeys.ENTITY_NOT_FOUND;
import static com.sap.olingo.jpa.processor.core.api.example.JPAExampleModifyException.MessageKeys.MODIFY_NOT_ALLOWED;
import static com.sap.olingo.jpa.processor.core.api.example.JPAExampleModifyException.MessageKeys.WILDCARD_RANGE_NOT_SUPPORTED;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.regex.Pattern;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.SingularAttribute;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.commons.api.http.HttpStatusCode;
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.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler;
import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair;
import com.sap.olingo.jpa.processor.core.api.JPAODataClaimProvider;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult;
import com.sap.olingo.jpa.processor.core.processor.JPAModifyUtil;
import com.sap.olingo.jpa.processor.core.processor.JPARequestEntity;
import com.sap.olingo.jpa.processor.core.processor.JPARequestLink;
/**
* Example implementation at a CUD handler. The main purpose is rapid prototyping.
* <p/>
* The implementation requires Getter and Setter. This includes getter for collection properties and collection
* navigation properties that return at least empty collections.<br/>
* To link entities constructor injection is used. So each dependent entity needs a constructor that takes a entity type
* it depends on as parameter.
* @author Oliver Grande
*
*/
public class JPAExampleCUDRequestHandler extends JPAAbstractCUDRequestHandler {
private final Map<Object, JPARequestEntity> entityBuffer;
private final LocalDateTime now;
public JPAExampleCUDRequestHandler() {
entityBuffer = new HashMap<>();
// Doing so all the changes of one request get the same updatedAt
now = LocalDateTime.now(ZoneId.of("UTC"));
new Date();
}
@Override
public Object createEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException {
// POST an Entity
Object instance = createOneEntity(requestEntity, null);
if (requestEntity.getKeys().isEmpty()) {
if (!hasGeneratedKey(requestEntity, em)) {
final Object old = em.find(requestEntity.getEntityType().getTypeClass(),
requestEntity.getModifyUtil().createPrimaryKey(requestEntity.getEntityType(), instance));
if (old != null)
throw new JPAExampleModifyException(ENTITY_ALREADY_EXISTS, HttpStatusCode.BAD_REQUEST);
} else {
// Pre-fill granted ID, so it can be used for deep inserts
em.persist(instance);
}
} else {
// POST on Link only
// https://issues.oasis-open.org/browse/ODATA-1294
instance = findEntity(requestEntity, em);
}
processRelatedEntities(requestEntity.getRelatedEntities(), instance, requestEntity.getModifyUtil(), em);
setAuditInformation(instance, requestEntity.getClaims(), true);
em.persist(instance);
return instance;
}
@Override
public void deleteEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessException {
final Object instance = em.find(requestEntity.getEntityType().getTypeClass(),
requestEntity.getModifyUtil().createPrimaryKey(requestEntity.getEntityType(), requestEntity.getKeys(),
requestEntity.getEntityType()));
if (instance != null)
em.remove(instance);
}
@Override
public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em,
final HttpMethod method) throws ODataJPAProcessException {
if (method == HttpMethod.PATCH || method == HttpMethod.DELETE) {
Object instance = em.find(requestEntity.getEntityType().getTypeClass(), requestEntity.getModifyUtil()
.createPrimaryKey(requestEntity.getEntityType(), requestEntity.getKeys(), requestEntity.getEntityType()));
if (instance == null) {
instance = createOneEntity(requestEntity, null);
requestEntity.getModifyUtil().setPrimaryKey(requestEntity.getEntityType(), requestEntity.getKeys(), instance);
return new JPAUpdateResult(true, instance);
} else {
return updateFoundEntity(requestEntity, em, instance);
}
}
return super.updateEntity(requestEntity, em, method);
}
@Override
public void validateChanges(final EntityManager em) throws ODataJPAProcessException {
for (final Entry<Object, JPARequestEntity> entity : entityBuffer.entrySet())
processBindingLinks(entity.getValue().getRelationLinks(), entity.getKey(), entity.getValue().getModifyUtil(), em);
}
private JPAUpdateResult updateFoundEntity(final JPARequestEntity requestEntity, final EntityManager em,
final Object instance) throws ODataJPAProcessorException, ODataJPAInvocationTargetException {
requestEntity.getModifyUtil().setAttributesDeep(requestEntity.getData(), instance, requestEntity
.getEntityType());
updateLinks(requestEntity, em, instance);
setAuditInformation(instance, requestEntity.getClaims(), false);
return new JPAUpdateResult(false, instance);
}
private void checkAuthorizationsOneClaim(final JPAProtectionInfo protectionInfo, final Object value,
final List<JPAClaimsPair<?>> pairs) throws JPAExampleModifyException {
boolean match = false;
for (final JPAClaimsPair<?> pair : pairs)
if (protectionInfo.supportsWildcards())
match = checkAuthorizationsOnePairWithWildcard(value, match, pair);
else
match = checkAuthorizationsOnePair(value, match, pair);
if (!match)
throw new JPAExampleModifyException(MODIFY_NOT_ALLOWED, HttpStatusCode.FORBIDDEN);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private boolean checkAuthorizationsOnePair(final Object value, boolean match, final JPAClaimsPair<?> pair)
throws JPAExampleModifyException {
if (!pair.hasUpperBoundary &&
("*".equals(pair.min) || value.equals(pair.min))) {
match = true;
} else if (pair.hasUpperBoundary) {
if (!(value instanceof Comparable<?>))
throw new JPAExampleModifyException(MODIFY_NOT_ALLOWED, HttpStatusCode.FORBIDDEN);
if (((Comparable) value).compareTo(pair.min) >= 0
&& ((Comparable) value).compareTo(pair.max) <= 0)
match = true;
}
return match;
}
private boolean checkAuthorizationsOnePairWithWildcard(final Object value, boolean match, final JPAClaimsPair<?> pair)
throws JPAExampleModifyException {
if (pair.hasUpperBoundary) {
final String minPrefix = determineAuthorizationPrefix(pair.min);
final String maxPrefix = determineAuthorizationPrefix(pair.max);
final String minComparator = ((String) value).substring(0, minPrefix.length());
final String maxComparator = ((String) value).substring(0, maxPrefix.length());
if (minComparator.compareTo(minPrefix) >= 0
&& maxComparator.compareTo(maxPrefix) <= 0)
match = true;
} else {
// '+' and '_' --> .
// '*' and '%' --> .+
final String minPattern = ((String) pair.minAs()).replace("\\.", "\\#").replaceAll("[+_]", ".")
.replaceAll("[*%]", ".+");
if (Pattern.matches(minPattern, (String) value))
match = true;
}
return match;
}
private void checkAuthorities(final Object instance, final JPAStructuredType entityType,
final Optional<JPAODataClaimProvider> claims, final JPAModifyUtil modifyUtility)
throws JPAExampleModifyException {
try {
final List<JPAProtectionInfo> protections = entityType.getProtections();
if (!protections.isEmpty()) {
final JPAODataClaimProvider claimsProvider = claims.orElseThrow(
() -> new JPAExampleModifyException(MODIFY_NOT_ALLOWED, HttpStatusCode.FORBIDDEN));
for (final JPAProtectionInfo protectionInfo : protections) {
final Object value = determineValue(instance, modifyUtility, protectionInfo);
final List<JPAClaimsPair<?>> pairs = claimsProvider.get(protectionInfo.getClaimName());
if (pairs.isEmpty())
throw new JPAExampleModifyException(MODIFY_NOT_ALLOWED, HttpStatusCode.FORBIDDEN);
checkAuthorizationsOneClaim(protectionInfo, value, pairs);
}
}
} catch (final ODataJPAModelException | NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
throw new JPAExampleModifyException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private Object createInstance(final Constructor<?> cons, final Object parent) throws ODataJPAProcessorException {
try {
if (cons.getParameterCount() == 1)
return cons.newInstance(parent);
return cons.newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
private Object createOneEntity(final JPARequestEntity requestEntity,
final Object parent) throws ODataJPAProcessException {
final Object instance = createInstance(getConstructor(requestEntity.getEntityType(), parent), parent);
requestEntity.getModifyUtil().setAttributesDeep(requestEntity.getData(), instance, requestEntity.getEntityType());
checkAuthorities(instance, requestEntity.getEntityType(), requestEntity.getClaims(), requestEntity.getModifyUtil());
entityBuffer.put(instance, requestEntity);
return instance;
}
private String determineAuthorizationPrefix(final Object restriction) throws JPAExampleModifyException {
final String[] minPrefix = ((String) restriction).split("[*%+_]");
if (minPrefix.length > 1)
throw new JPAExampleModifyException(WILDCARD_RANGE_NOT_SUPPORTED, HttpStatusCode.NOT_IMPLEMENTED);
return minPrefix[0];
}
private Object determineValue(final Object instance, final JPAModifyUtil modifyUtility,
final JPAProtectionInfo protectionInfo) throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
Object value = instance;
for (final JPAElement element : protectionInfo.getPath().getPath()) {
final JPAAttribute attribute = (JPAAttribute) element;
final String getterName = "get" + modifyUtility.buildMethodNameSuffix(attribute);
final Method getter = value.getClass().getMethod(getterName);
value = getter.invoke(value);
}
return value;
}
private Object findEntity(final JPARequestEntity requestEntity, final EntityManager em)
throws ODataJPAProcessorException,
ODataJPAInvocationTargetException {
final Object key = requestEntity.getModifyUtil().createPrimaryKey(requestEntity.getEntityType(), requestEntity
.getKeys(), requestEntity.getEntityType());
return em.getReference(requestEntity.getEntityType().getTypeClass(), key);
}
private Constructor<?> getConstructor(final JPAStructuredType st, final Object parentInstance)
throws ODataJPAProcessorException {
// If a parent exists, try to use a constructor that accepts the parent
if (parentInstance != null) try {
return st.getTypeClass().getConstructor(parentInstance.getClass());
} catch (NoSuchMethodException | SecurityException e) {} // NOSONAR
try {
return st.getTypeClass().getConstructor();
} catch (NoSuchMethodException | SecurityException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
/**
* The method is able to create OneTonOne relations as well as OneToMany relations. ManyToOne relations cloud only be
* handled in case a corresponding OneToMany relation exists.
* @param relationLinks
* @param instance
* @param utility
* @param em
* @throws ODataJPAProcessException
*/
private void processBindingLinks(final Map<JPAAssociationPath, List<JPARequestLink>> relationLinks,
final Object instance, final JPAModifyUtil utility, final EntityManager em) throws ODataJPAProcessException {
for (final Entry<JPAAssociationPath, List<JPARequestLink>> entity : relationLinks.entrySet()) {
final JPAAssociationPath pathInfo = entity.getKey();
for (final JPARequestLink requestLink : entity.getValue()) {
final Object targetKey = utility.createPrimaryKey((JPAEntityType) pathInfo.getTargetType(), requestLink
.getRelatedKeys(), pathInfo.getSourceType());
final Object target = em.find(pathInfo.getTargetType().getTypeClass(), targetKey);
if (target == null)
throw new JPAExampleModifyException(ENTITY_NOT_FOUND, HttpStatusCode.BAD_REQUEST);
try {
final JPAAssociationAttribute partner = pathInfo.getPartner();
if (pathInfo.isCollection() && partner != null) {
utility.linkEntities(target, instance, partner.getPath());
// The following line would set the link also on the source side. Unfortunately can this lead to a deep
// expand e.g. in case of hierarchies, as JPA load association lazy.
// util.linkEntities(instance, target, pathInfo); //NOSONAR
} else
utility.linkEntities(instance, target, pathInfo);
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
}
}
private void processRelatedEntities(final Map<JPAAssociationPath, List<JPARequestEntity>> relatedEntities,
final Object parentInstance, final JPAModifyUtil utility, final EntityManager em)
throws ODataJPAProcessException {
for (final Map.Entry<JPAAssociationPath, List<JPARequestEntity>> entity : relatedEntities.entrySet()) {
final JPAAssociationPath pathInfo = entity.getKey();
for (final JPARequestEntity requestEntity : entity.getValue()) {
final Object newInstance = createOneEntity(requestEntity, parentInstance);
utility.linkEntities(parentInstance, newInstance, pathInfo);
try {
final JPAAssociationAttribute attribute = pathInfo.getPartner();
if (attribute != null) {
utility.linkEntities(newInstance, parentInstance, attribute.getPath());
}
} catch (final ODataJPAModelException e) {
throw new ODataJPAProcessorException(e, HttpStatusCode.INTERNAL_SERVER_ERROR);
}
processRelatedEntities(requestEntity.getRelatedEntities(), newInstance, utility, em);
}
}
}
private void setAuditInformation(final Object instance, final Optional<JPAODataClaimProvider> claims,
final boolean created) {
if (instance instanceof final JPAExampleAuditable auditable) {
if (created) {
auditable.setCreatedAt(now);
claims.ifPresent(claim -> auditable.setCreatedBy(claim.user().orElse("")));
}
auditable.setUpdatedAt(now);
claims.ifPresent(claim -> auditable.setUpdatedBy(claim.user().orElse("")));
}
}
private void updateLinks(final JPARequestEntity requestEntity, final EntityManager em, final Object instance)
throws ODataJPAProcessorException, ODataJPAInvocationTargetException {
if (requestEntity.getRelationLinks() != null)
for (final Entry<JPAAssociationPath, List<JPARequestLink>> links : requestEntity.getRelationLinks().entrySet()) {
for (final JPARequestLink link : links.getValue()) {
final Object related = em.find(link.getEntityType().getTypeClass(), requestEntity.getModifyUtil()
.createPrimaryKey(link.getEntityType(), link.getRelatedKeys(), link.getEntityType()));
requestEntity.getModifyUtil().linkEntities(instance, related, links.getKey());
}
}
}
private boolean hasGeneratedKey(final JPARequestEntity requestEntity, final EntityManager em) {
final JPAEntityType et = requestEntity.getEntityType();
return em.getMetamodel()
.getEntities()
.stream()
.filter(type -> type.getName().equals(et.getExternalName()))
.findFirst()
.map(jpaEt -> hasGeneratedKeyInternal(et, jpaEt))
.orElse(false);
}
private boolean hasGeneratedKeyInternal(final JPAEntityType et, final EntityType<?> jpaEt) {
try {
if (jpaEt.hasSingleIdAttribute()) {
final JPAAttribute key = et.getKey().get(0);
final SingularAttribute<?, ?> at = jpaEt.getId(key.getType());
if (at != null &&
((AnnotatedElement) at.getJavaMember()).getAnnotation(GeneratedValue.class) != null)
return true;
}
return false;
} catch (final ODataJPAModelException e) {
return false;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExampleAuditable.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExampleAuditable.java | package com.sap.olingo.jpa.processor.core.api.example;
import java.time.LocalDateTime;
public interface JPAExampleAuditable {
void setCreatedBy(final String user);
void setCreatedAt(final LocalDateTime dateTime);
void setUpdatedBy(final String user);
void setUpdatedAt(final LocalDateTime dateTime);
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProvider.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProvider.java | package com.sap.olingo.jpa.processor.core.api.example;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jakarta.persistence.EntityManager;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriResourceCount;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import com.sap.olingo.jpa.metadata.api.JPARequestParameterMap;
import com.sap.olingo.jpa.processor.core.api.JPAODataPage;
import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataPathInformation;
import com.sap.olingo.jpa.processor.core.query.JPACountQuery;
public class JPAExamplePagingProvider implements JPAODataPagingProvider {
private static final Object lock = new Object();
private static final int DEFAULT_BUFFER_SIZE = 100;
private final Map<String, Integer> maxPageSizes;
private final Map<Integer, CacheEntry> pageCache;
private final Queue<Integer> index;
private final int cacheSize;
public JPAExamplePagingProvider(final Map<String, Integer> pageSizes) {
this(pageSizes, DEFAULT_BUFFER_SIZE);
}
public JPAExamplePagingProvider(final Map<String, Integer> pageSizes, final int bufferSize) {
maxPageSizes = Collections.unmodifiableMap(pageSizes);
pageCache = new HashMap<>(bufferSize);
cacheSize = bufferSize;
index = new LinkedList<>();
}
@Override
public Optional<JPAODataPage> getNextPage(@Nonnull final String skipToken, final OData odata,
final ServiceMetadata serviceMetadata, final JPARequestParameterMap requestParameter, final EntityManager em) {
final var previousPage = pageCache.get(Integer.valueOf(skipToken.replace("'", "")));
if (previousPage != null) {
// Calculate next page
final Integer skip = previousPage.page().skip() + previousPage.page().top();
final var top = (int) ((skip + previousPage.page().top()) < previousPage.maxTop() ? previousPage
.page().top() : previousPage.maxTop() - skip);
// Create a new skip token if next page is not the last one
Integer nextToken = null;
if (skip + previousPage.page().top() < previousPage.maxTop())
nextToken = Objects.hash(previousPage.page().uriInfo(), skip, top);
final var page = new JPAODataPage(previousPage.page().uriInfo(), skip, top, nextToken);
if (nextToken != null)
addToCache(page, previousPage.maxTop());
return Optional.of(page);
}
// skip token not found => let JPA Processor handle this by return http.gone
return Optional.empty();
}
@Override
public Optional<JPAODataPage> getFirstPage(final JPARequestParameterMap requestParameter,
final JPAODataPathInformation pathInformation, final UriInfo uriInfo, @Nullable final Integer preferredPageSize,
final JPACountQuery countQuery, final EntityManager em) throws ODataApplicationException {
final var resourceParts = uriInfo.getUriResourceParts();
final var root = resourceParts.get(0);
final var leaf = resourceParts.get(resourceParts.size() - 1);
// Paging will only be done for Entity Sets
if (root instanceof final UriResourceEntitySet entitySet
&& !(leaf instanceof UriResourceCount)) {
// Not last is count!!
// Check if Entity Set shall be packaged
final var maxSize = maxPageSizes.get(entitySet.getEntitySet().getName());
if (maxSize != null) {
// Read $top and $skip
final Integer skipValue = uriInfo.getSkipOption() != null ? uriInfo.getSkipOption().getValue() : 0;
final var topValue = uriInfo.getTopOption() != null ? uriInfo.getTopOption().getValue() : null;
// Determine page size
final var pageSize = preferredPageSize != null && preferredPageSize < maxSize ? preferredPageSize : maxSize;
if (topValue != null && topValue <= pageSize)
return Optional.of(new JPAODataPage(uriInfo, skipValue, topValue, null));
// Determine end of list
final var maxResults = countQuery.countResults();
final Long count = topValue != null && (topValue + skipValue) < maxResults
? topValue.longValue() : maxResults - skipValue;
final Long last = topValue != null && (topValue + skipValue) < maxResults
? (topValue + skipValue) : maxResults;
// Create a unique skip token if needed
Integer skipToken = null;
if (pageSize < count)
skipToken = Objects.hash(uriInfo, skipValue, pageSize);
// Create page information
final var page = new JPAODataPage(uriInfo, skipValue, pageSize, skipToken);
// Cache page to be able to fulfill next link based request
if (skipToken != null)
addToCache(page, last);
return Optional.of(page);
}
}
return Optional.empty();
}
private void addToCache(final JPAODataPage page, final Long count) {
synchronized (lock) {
if (pageCache.size() == cacheSize)
pageCache.remove(index.poll());
pageCache.put((Integer) page.skipToken(), new CacheEntry(count, page));
index.add((Integer) page.skipToken());
}
}
private static record CacheEntry(Long maxTop, JPAODataPage page) {}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/modify/JPAMapCollectionResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/modify/JPAMapCollectionResult.java | package com.sap.olingo.jpa.processor.core.modify;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.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.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.converter.JPACollectionResult;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.converter.JPATuple;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
class JPAMapCollectionResult extends JPAMapBaseResult implements JPACollectionResult {
private Map<String, List<Object>> converted;
private final JPAAssociationPath path;
public JPAMapCollectionResult(final JPAEntityType et, final Collection<?> values,
final Map<String, List<String>> requestHeaders, final JPACollectionAttribute attribute)
throws ODataJPAModelException, ODataJPAProcessorException {
super(et, requestHeaders);
this.path = attribute.asAssociation();
result = convertToTuple(et, values, attribute);
}
@SuppressWarnings("unchecked")
private List<Tuple> convertToTuple(final JPAEntityType et, final Collection<?> values,
final JPACollectionAttribute attribute) throws ODataJPAProcessorException, ODataJPAModelException {
final List<Tuple> tupleList = new ArrayList<>();
for (final Object value : values) {
final JPATuple tuple = new JPATuple();
if (attribute.isComplex()) {
for (final JPAPath p : attribute.getStructuredType().getPathList())
convertPathToTuple(tuple, (Map<String, Object>) value, et.getPath(this.path.getAlias()
+ JPAPath.PATH_SEPARATOR + p.getAlias()), 1);
} else {
tuple.addElement(path.getAlias(), attribute.getType(), value);
}
tupleList.add(tuple);
}
return tupleList;
}
@Override
public void convert(final JPAResultConverter converter) throws ODataApplicationException {
converted = converter.getCollectionResult(this, Collections.emptySet());
}
@Override
public Collection<Object> getPropertyCollection(final String key) {
return converted.get(ROOT_RESULT_KEY);
}
@Override
public JPAAssociationPath getAssociation() {
return path;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/modify/JPAEntityNavigationLinkResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/modify/JPAEntityNavigationLinkResult.java | package com.sap.olingo.jpa.processor.core.modify;
import static java.util.stream.Collectors.joining;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
final class JPAEntityNavigationLinkResult extends JPANavigationLinkResult {
JPAEntityNavigationLinkResult(final JPAEntityType et, final Collection<?> values,
final Map<String, List<String>> requestHeaders, final JPAResultConverter converter,
final List<JPAPath> foreignKey) throws ODataJPAModelException, ODataApplicationException {
super(et, requestHeaders);
for (final Object value : values) {
final var key = buildConcatenatedForeignKey(foreignKey, value);
final List<Tuple> part = result.computeIfAbsent(key, k -> new ArrayList<Tuple>());
part.add(new JPAEntityResult(et, value, requestHeaders, converter).getResult(ROOT_RESULT_KEY).get(0));
}
}
@Override
protected Map<String, Object> entryAsMap(final Object entry) throws ODataJPAProcessorException {
return helper.buildGetterMap(entry);
}
private String buildConcatenatedForeignKey(final List<JPAPath> foreignKey, final Object value)
throws ODataJPAProcessorException {
final var properties = entryAsMap(value);
return foreignKey.stream()
.map(column -> (properties.get(column.getLeaf().getInternalName())).toString())
.collect(joining(JPAPath.PATH_SEPARATOR));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/modify/JPANavigationLinkResult.java | jpa/odata-jpa-processor/src/main/java/com/sap/olingo/jpa/processor/core/modify/JPANavigationLinkResult.java | package com.sap.olingo.jpa.processor.core.modify;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Tuple;
import org.apache.olingo.server.api.ODataApplicationException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.api.JPAODataPageExpandInfo;
import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult;
import com.sap.olingo.jpa.processor.core.converter.JPAResultConverter;
import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException;
import com.sap.olingo.jpa.processor.core.query.JPAConvertibleResult;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollection;
import com.sap.olingo.jpa.processor.core.serializer.JPAEntityCollectionExtension;
abstract class JPANavigationLinkResult extends JPACreateResult implements JPAConvertibleResult {
Map<String, JPAEntityCollectionExtension> odataResult;
final Map<String, List<Tuple>> result;
JPANavigationLinkResult(final JPAEntityType et, final Map<String, List<String>> requestHeaders)
throws ODataJPAModelException {
super(et, requestHeaders);
this.result = new HashMap<>();
}
@Override
public Map<String, JPAEntityCollectionExtension> asEntityCollection(final JPAResultConverter converter)
throws ODataApplicationException {
convert(converter);
return odataResult;
}
@Override
public JPAEntityCollectionExtension getEntityCollection(final String key, final JPAResultConverter converter,
final JPAAssociationPath association, final List<JPAODataPageExpandInfo> expandInfo)
throws ODataApplicationException {
if (odataResult == null)
asEntityCollection(converter);
return odataResult.containsKey(key) ? odataResult.get(key) : new JPAEntityCollection();
}
@SuppressWarnings("unchecked")
@Override
public void convert(final JPAResultConverter converter) throws ODataApplicationException {
odataResult = (Map<String, JPAEntityCollectionExtension>) converter.getResult(this, Collections.emptySet());
}
@Override
public void putChildren(final Map<JPAAssociationPath, JPAExpandResult> childResults)
throws ODataApplicationException {
// Not needed for JPANavigationLinkResult
}
@Override
public List<Tuple> getResult(final String key) {
return result.get(key);
}
@Override
public List<Tuple> removeResult(final String key) {
return result.put(key, null);
}
@Override
public Map<String, List<Tuple>> getResults() {
return result;
}
@Override
protected String determineLocale(final Map<String, Object> descGetterMap, final JPAPath localeAttribute,
final int index) throws ODataJPAProcessorException {
// Not needed for JPAMapNavigationLinkResult
return null;
}
}
| 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.