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-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeleteRestrictionsProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeleteRestrictionsProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum DeleteRestrictionsProperties implements PropertyAccess {
DELETABLE("Deletable"),
NON_DELETABLE_NAVIGATION_PROPERTIES("NonDeletableNavigationProperties"),
MAX_LEVELS("MaxLevels"),
DESCRIPTION("Description"),
LONG_DESCRIPTION("LongDescription");
private final String property;
private DeleteRestrictionsProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeepInsertSupport.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeepInsertSupport.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href=
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L677"><i>DeepInsertSupport</i></a>:
* <br>
* Deep Insert Support of the annotated resource (the whole service, an entity set, or a collection-valued resource)
* <p>
*
* AppliesTo: EntitySet
*
* @author Oliver Grande
* Created: 01.05.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET })
public @interface DeepInsertSupport {
/**
* Annotation target supports deep inserts.
*/
boolean supported() default true;
/**
* Annotation target supports accepting and returning nested entities annotated with the `Core.ContentID` instance
* annotation.
*/
boolean contentIDSupported() default true;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/ExpandRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/ExpandRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L524"><i>ExpandRestrictions</i></a>:
* Restrictions on expand expressions.
* <p>
*
* AppliesTo: EntitySet Singleton
* @author Oliver Grande
* Created: 29.12.2022
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET, Applicability.SINGLETON })
public @interface ExpandRestrictions {
/**
* $expand is supported
*/
boolean expandable() default true;
/**
* These properties cannot be used in expand expressions.
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g. <i>address/cityName</i>.
*/
String[] nonExpandableProperties() default {};
// $expand not supported
//<Property Name="StreamsExpandable" Type="Edm.Boolean" Nullable="false" DefaultValue="false">
// <Annotation Term="Core.Description" String="$expand is supported for stream properties and media streams" />
//</Property>
//<Property Name="NonExpandableStreamProperties" Type="Collection(Edm.PropertyPath)" Nullable="false">
// <Annotation Term="Core.Description" String="These stream properties cannot be used in expand expressions" />
// <Annotation Term="Core.RequiresType" String="Edm.Stream" />
//</Property>
/**
* The maximum number of levels that can be expanded in a expand expression. A value of -1 indicates there is no
* restriction.
*/
int maxLevels() default -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-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/ExpandRestrictionsProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/ExpandRestrictionsProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum ExpandRestrictionsProperties implements PropertyAccess {
EXPANDABLE("Expandable"),
NON_EXPANDABLE_PROPERTIES("NonExpandableProperties"),
MAX_LEVELS("MaxLevels");
private final String property;
private ExpandRestrictionsProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/FilterRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/FilterRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation
* <a href=
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L430"><i>FilterRestrictions</i></a>:
* <br>
* Restrictions on filter expressions.
* <p>
*
* AppliesTo: EntitySet
* @author Oliver Grande
* Created: 26.04.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET })
public @interface FilterRestrictions {
/** $filter is supported */
boolean filterable() default true;
/**
* $filter is required
*/
boolean requiresFilter() default false;
/**
* Optional: These properties must be specified in the $filter clause (properties of derived types are not allowed
* here)
* <p>
* The properties are given as an array of attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] requiredProperties() default {};
/**
* Optional: These properties that are not allowed in a $filter clause (properties of derived types are not allowed
* here)
* <p>
* The properties are given as an array of attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] nonFilterableProperties() default {};
/**
* Not supported yet
* Allowed subset of expressions
* @return
*/
// FilterExpressionRestrictionType[] filterExpressionRestrictions() default {};
//
// @interface FilterExpressionRestrictionType {
// /**
// * Path to the restricted property
// * <p>
// * The properties are given as an attribute path.
// */
// String property();
//
// FilterExpressionType allowedExpressions();
// }
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/CountRestrictionsProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/CountRestrictionsProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum CountRestrictionsProperties implements PropertyAccess {
COUNTABLE("Countable"),
NON_COUNTABLE_PROPERTIES("NonCountableProperties"),
NON_COUNTABLE_NAVIGATION_PROPERTIES("NonCountableNavigationProperties");
private final String property;
private CountRestrictionsProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/InsertRestrictionsProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/InsertRestrictionsProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum InsertRestrictionsProperties implements PropertyAccess {
INSERTABLE("Insertable"),
NON_INSERTABLE_PROPERTIES("NonInsertableProperties"),
NON_INSERTABLE_NAVIGATION_PROPERTIES("NonInsertableNavigationProperties"),
REQUIRED_PROPERTIES("RequiredProperties"),
MAX_LEVELS("MaxLevels"),
DESCRIPTION("Description"),
LONG_DESCRIPTION("LongDescription");
private final String property;
private InsertRestrictionsProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/SortRestrictionsProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/SortRestrictionsProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum SortRestrictionsProperties implements PropertyAccess {
SORTABLE("Sortable"),
ASCENDING_ONLY_PROPERTIES("AscendingOnlyProperties"),
DESCENDING_ONLE_PROPERTIES("DescendingOnlyProperties"),
NON_SORTABLE_PROPERTIES("NonSortableProperties");
private final String property;
private SortRestrictionsProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/UpdateRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/UpdateRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L690"><i>UpdateRestrictions</i></a>:
* <br>
* Restrictions on update operations.
* <p>
*
* AppliesTo: EntitySet, Singleton
* @author Oliver Grande
* Created: 26.04.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET, Applicability.SINGLETON })
public @interface UpdateRestrictions {
/**
* Entities can be updated
*/
boolean updatable() default true;
/**
* Entities can be upserted
*/
boolean upsertable() default false;
// /**
// * Delta handling not supported yet
// * Entities can be inserted, updated, and deleted via a PATCH request with a delta payload
// */
// boolean deltaUpdateSupported() default false;
/**
* Supported HTTP Methods (PUT or PATCH) for updating an entity. If null, PATCH SHOULD be supported and PUT MAY be
* supported.<br>
*/
UpdateMethod updateMethod() default UpdateMethod.NOT_SPECIFIED;
//<Property Name="FilterSegmentSupported" Type="Edm.Boolean" Nullable="false" DefaultValue="true">
// <Annotation Term="Core.Description" String="Members of collections can be updated via a PATCH request with a `/$filter(...)/$each` segment" />
//</Property>
//<Property Name="TypecastSegmentSupported" Type="Edm.Boolean" Nullable="false" DefaultValue="true">
// <Annotation Term="Core.Description" String="Members of collections can be updated via a PATCH request with a type-cast segment and a `/$each` segment" />
//</Property>
/**
* These structural properties cannot be specified on update
*/
String[] nonUpdatableProperties() default {};
/**
* These navigation properties do not allow rebinding
*/
String[] nonUpdatableNavigationProperties() default {};
/**
* These structural properties must be specified on update
*/
String[] requiredProperties() default {};
/**
* The maximum number of navigation properties that can be traversed when addressing the collection or entity to
* update. A value of -1 indicates there is no restriction.
*/
int maxLevels() default -1;
//<Property Name="Permissions" Type="Collection(Capabilities.PermissionType)" Nullable="true">
// <Annotation Term="Core.Description" String="Required permissions. One of the specified sets of scopes is required to perform the update." />
//</Property>
//<Property Name="QueryOptions" Type="Capabilities.ModificationQueryOptionsType" Nullable="true">
// <Annotation Term="Core.Description" String="Support for query options with update requests" />
//</Property>
//<Property Name="CustomHeaders" Type="Collection(Capabilities.CustomParameter)" Nullable="false">
// <Annotation Term="Core.Description" String="Supported or required custom headers" />
//</Property>
//<Property Name="CustomQueryOptions" Type="Collection(Capabilities.CustomParameter)" Nullable="false">
// <Annotation Term="Core.Description" String="Supported or required custom query options" />
//</Property>
/**
* A brief description of the request.
* <p>
* Currently only one language supported.
*/
String description() default "";
/**
* A lengthy description of the request.
* Currently only one language supported.
*/
String longDescription() default "";
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/SortRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/SortRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L500"><i>SortRestrictions</i></a>:
* <br>
* Restrictions on orderby expressions.
* <p>
*
* AppliesTo: EntitySet
*
* @author Oliver Grande
* Created: 26.04.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET })
public @interface SortRestrictions {
/**
* $orderby is supported
* @return
*/
boolean sortable() default true;
/**
* These properties can only be used for sorting in Ascending order.
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] ascendingOnlyProperties() default {};
/**
* These properties can only be used for sorting in Descending order.
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] descendingOnlyProperties() default {};
/**
* These structural properties cannot be used in orderby expressions
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] nonSortableProperties() default {};
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/CountRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/CountRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
*
* OData core annotation <a href=
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L210"><i>CountRestrictions</i></a>:
* <br>
* Restrictions on /$count path suffix and $count=true system query option
* <p>
* @author Oliver Grande
* @since 1.1.1
* 12.01.2023
*/
@Retention(RUNTIME)
@Target({ TYPE, FIELD })
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET, Applicability.SINGLETON })
public @interface CountRestrictions {
/**
* Entities can be counted (only valid if targeting an entity set).
*/
boolean countable() default true;
/**
* Members of these collection properties cannot be counted.
* <p>
* The properties are given as an array of attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] nonCountableProperties() default {};
/**
* Members of these navigation properties cannot be counted
* <p>
* The navigation properties are given as an array of attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] nonCountableNavigationProperties() default {};
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/UpdateRestrictionsProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/UpdateRestrictionsProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum UpdateRestrictionsProperties implements PropertyAccess {
UPDATEABLE("Updatable"),
UPSERTABLE("Upsertable"),
UPDATE_METHOD("UpdateMethod"),
NON_UPDATEABLE_PROPERTIES("NonUpdatableProperties"),
NON_UPDATEABLE_NAVIGATION_PROPERTIES("NonUpdatableNavigationProperties"),
REQUIRED_PROPERTIES("RequiredProperties"),
MAX_LEVELS("MaxLevels"),
DESCRIPTION("Description"),
LONG_DESCRIPTION("LongDescription");
private final String property;
private UpdateRestrictionsProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeepInsertSupportProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeepInsertSupportProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum DeepInsertSupportProperties implements PropertyAccess {
SUPPORTED("supported"),
CONTENT_ID_SUPPORTED("contentIDSupported");
private final String property;
private DeepInsertSupportProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/UpdateMethod.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/UpdateMethod.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import org.apache.olingo.commons.api.http.HttpMethod;
/**
* @author Oliver Grande
* Created: 29.04.2021
*
*/
public enum UpdateMethod {
PATCH(HttpMethod.PATCH),
PUT(HttpMethod.PUT),
NOT_SPECIFIED(null);
private final HttpMethod value;
/**
* @param verb
*/
UpdateMethod(final HttpMethod verb) {
this.value = verb;
}
public HttpMethod getValue() {
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-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/Terms.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/Terms.java | package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.TermAccess;
public enum Terms implements TermAccess {
COUNT_RESTRICTIONS("CountRestrictions"),
DEEP_INSERT_SUPPORT("DeepInsertSupport"),
DEEP_UPDATE_SUPPORT("DeepUpdateSupport"),
DELETE_RESTRICTIONS("DeleteRestrictions"),
EXPAND_RESTRICTIONS("ExpandRestrictions"),
FILTER_RESTRICTIONS("FilterRestrictions"),
INSERT_RESTRICTIONS("InsertRestrictions"),
SORT_RESTRICTIONS("SortRestrictions"),
UPDATE_RESTRICTIONS("UpdateRestrictions");
private final String term;
Terms(final String term) {
this.term = term;
}
@Override
public String term() {
return term;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/InsertRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/InsertRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L600"><i>InsertRestrictions</i></a>:
* <br>
* Restrictions on insert operations.
* <p>
*
* AppliesTo: EntitySet, EntityType
* @author Oliver Grande
* Created: 26.04.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET })
public @interface InsertRestrictions {
/**
* If <b>true</b>: entities can be inserted. Default: <b>false</b>
* @return
*/
boolean insertable() default false;
// https://docs.oasis-open.org/odata/odata-csdl-xml/v4.01/odata-csdl-xml-v4.01.html#sec_PathExpressions
/**
* These structural attributes cannot be specified on insert
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] nonInsertableProperties() default {};
/**
* These navigation attributes do not allow deep inserts
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] nonInsertableNavigationProperties() default {};
/**
* These structural attributes must be specified on insert
* <p>
* The properties are given as an array attributes path. In case the path
* is composed, path segments joined together by forward slashes (/) e.g <i>address/cityName</i>.
*/
String[] requiredProperties() default {};
/**
* The maximum number of navigation properties that can be traversed when addressing the collection to insert into. A
* value of -1 indicates there is no restriction..
*/
int maxLevels() default -1;
// <Property Name="TypecastSegmentSupported" Type="Edm.Boolean" Nullable="false" DefaultValue="true">
// <Annotation Term="Core.Description" String="Entities of a specific derived type can be created by specifying a type-cast segment" />
// </Property>
// <Property Name="Permissions" Type="Collection(Capabilities.PermissionType)" Nullable="true">
// <Annotation Term="Core.Description" String="Required permissions. One of the specified sets of scopes is required to perform the insert." />
// </Property>
// <Property Name="QueryOptions" Type="Capabilities.ModificationQueryOptionsType" Nullable="true">
// <Annotation Term="Core.Description" String="Support for query options with insert requests" />
// </Property>
// <Property Name="CustomHeaders" Type="Collection(Capabilities.CustomParameter)" Nullable="false">
// <Annotation Term="Core.Description" String="Supported or required custom headers" />
// </Property>
// <Property Name="CustomQueryOptions" Type="Collection(Capabilities.CustomParameter)" Nullable="false">
// <Annotation Term="Core.Description" String="Supported or required custom query options" />
// </Property>
/**
* A brief description of the request.
* <p>
* Currently only one language supported.
*/
String description() default "";
/**
* A lengthy description of the request.
* Currently only one language supported.
*/
String longDescription() default "";
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeepUpdateSupport.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeepUpdateSupport.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L774"><i>DeepUpdateSupport</i></a>:
* <br>
* Deep Update Support of the annotated resource (the whole service, an entity set, or a collection-valued resource)
* <p>
*
* AppliesTo: EntitySet
* @author Oliver Grande
* Created: 29.04.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET })
public @interface DeepUpdateSupport {
/**
* Annotation target supports deep updates
*/
boolean supported() default true;
/**
* Annotation target supports accepting and returning nested entities annotated with the `Core.ContentID` instance
* annotation.
*/
boolean contentIDSupported() default true;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeleteRestrictions.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/DeleteRestrictions.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <a href =
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L787"><i>DeleteRestrictions</i></a>:
* <br>
* Restrictions on delete operations.
* <p>
*
* AppliesTo: EntitySet Singleton EntityType
* @author Oliver Grande
* Created: 29.04.2021
*
*/
@Retention(RUNTIME)
@Target(TYPE)
@Vocabulary(alias = "Capabilities", appliesTo = { Applicability.ENTITY_SET, Applicability.SINGLETON })
public @interface DeleteRestrictions {
/**
* Entities can be deleted
*/
boolean deletable() default true;
/**
* These navigation properties do not allow DeleteLink requests
*/
String[] nonDeletableNavigationProperties() default {};
/**
* The maximum number of navigation properties that can be traversed when addressing the collection to delete from or
* the entity to delete. A value of -1 indicates there is no restriction.
*/
int maxLevels() default -1;
// <Property Name="FilterSegmentSupported" Type="Edm.Boolean" Nullable="false" DefaultValue="true">
// <Annotation Term="Core.Description" String="Members of collections can be updated via a PATCH request with a `/$filter(...)/$each` segment" />
// </Property>
// <Property Name="TypecastSegmentSupported" Type="Edm.Boolean" Nullable="false" DefaultValue="true">
// <Annotation Term="Core.Description" String="Members of collections can be updated via a PATCH request with a type-cast segment and a `/$each` segment" />
// </Property>
// <Property Name="Permissions" Type="Collection(Capabilities.PermissionType)" Nullable="true">
// <Annotation Term="Core.Description" String="Required permissions. One of the specified sets of scopes is required to perform the delete." />
// </Property>
// <Property Name="CustomHeaders" Type="Collection(Capabilities.CustomParameter)" Nullable="false">
// <Annotation Term="Core.Description" String="Supported or required custom headers" />
// </Property>
// <Property Name="CustomQueryOptions" Type="Collection(Capabilities.CustomParameter)" Nullable="false">
// <Annotation Term="Core.Description" String="Supported or required custom query options" />
// </Property>
/**
* A brief description of the request.
* <p>
* Currently only one language supported.
*/
String description() default "";
/**
* A lengthy description of the request.
* Currently only one language supported.
*/
String longDescription() default "";
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/FilterExpressionType.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/capabilities/terms/FilterExpressionType.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms;
/**
* @author Oliver Grande
* Created: 26.04.2021
*
*/
public enum FilterExpressionType {
/**
* Property can be used in a single `eq` clause.
*/
SINGLE_VALUE("SingleValue"),
/**
* Property can be used in multiple `eq` and `in` clauses, combined by `or` (which is logically equivalent to a
* single `in` clause)
*/
MULTI_VALUE("MultiValue"),
/**
* Property can be used in at most one `ge` and/or one `le` clause, separated by `and`.
*/
SINGLE_RANGE("SingleRange"),
/**
* The filter expression for this property consists of one or more interval expressions combined by `or`. A single
* interval expression is either a single comparison of the property and a literal value with `eq`, `le`, `lt`, `ge`,
* or `gt`, or pair of boundaries combined by `and` and enclosed in parentheses. The lower boundary is either `ge` or
* `gt`, the upper boundary either `le` or `lt`.
*/
MULTI_RANGE("MultiRange"),
/**
* String property can be used as first operand in `startswith`, `endswith`, and `contains` clauses.
*/
SEARCH_EXPRESSION("SearchExpression"),
/**
* The filter expression for this property consists of one or more interval expressions or string comparison functions
* combined by `or`. See {@linkplain #MULTI_RANGE} for a definition of an interval expression. See
* {@linkplain #SEARCH_EXPRESSION} for the
* allowed string comparison functions.
*/
MULTI_RANGE_SEARCH("MultiRangeOrSearchExpression");
private final String value;
/**
* @param value
*/
FilterExpressionType(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
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-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/general/Aliases.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/general/Aliases.java | package com.sap.olingo.jpa.metadata.odata.v4.general;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AliasAccess;
public enum Aliases implements AliasAccess {
CORE("Core"),
CAPABILITIES("Capabilities");
private final String alias;
Aliases(final String alias) {
this.alias = alias;
}
@Override
public String alias() {
return alias;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/general/Vocabulary.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/general/Vocabulary.java | /**
*
*/
package com.sap.olingo.jpa.metadata.odata.v4.general;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
@Retention(RUNTIME)
@Target(ANNOTATION_TYPE)
/**
* @author Oliver Grande
* @since 1.1.1
* 02.01.2023
*/
public @interface Vocabulary {
/**
* Alias given in the vocabulary definition. E.g. <em>Capabilities</em> for
* <a href=
* "https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml">Org.OData.Capabilities.V1</a>
*/
String alias();
/**
* Supported applicability. This could be a subset of the defined applicability.
*/
Applicability[] appliesTo();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaBasedODataAnnotationsProvider.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaBasedODataAnnotationsProvider.java | package com.sap.olingo.jpa.metadata.odata.v4.provider;
import static java.util.Objects.requireNonNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.JPAReferences;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataVocabularyReadException;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ReferenceList;
abstract class JavaBasedODataAnnotationsProvider implements AnnotationProvider {
final JavaAnnotationConverter converter;
final String packageName;
JavaBasedODataAnnotationsProvider(final JavaAnnotationConverter converter, final String name) {
this.converter = converter;
this.packageName = name;
}
@Override
public Collection<CsdlAnnotation> getAnnotations(@Nonnull final Applicability appliesTo,
final ODataAnnotatable annotatable, final JPAReferences references) {
final var annotations = requireNonNull(annotatable).javaAnnotations(packageName);
return requireNonNull(references).getTerms(getAlias(), requireNonNull(appliesTo)).stream()
.map(term -> annotations.get(term.getName()))
.filter(Objects::nonNull)
.map(a -> converter.convert(references, a, annotatable))
.map(converted -> converted.orElse(null))
.filter(Objects::nonNull)
.toList();
}
@Override
public void addReferences(final ReferenceList references) throws ODataVocabularyReadException {
try {
final var uri = getUri();
final var reference = references.addReference(uri, getPath());
reference.addInclude(getNameSpace(), getAlias());
} catch (final URISyntaxException e) {
throw new ODataVocabularyReadException(getAlias(), getPath(), e);
}
}
abstract String getAlias();
abstract URI getUri() throws URISyntaxException;
abstract String getNameSpace();
abstract String getPath();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaBasedCoreAnnotationsProvider.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaBasedCoreAnnotationsProvider.java | package com.sap.olingo.jpa.metadata.odata.v4.provider;
import java.net.URI;
import java.net.URISyntaxException;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.Immutable;
public class JavaBasedCoreAnnotationsProvider extends JavaBasedODataAnnotationsProvider {
static final String NAMESPACE = "Org.OData.Core.V1";
static final String ALIAS = "Core";
static final String PATH = "vocabularies/Org.OData.Core.V1.xml";
public JavaBasedCoreAnnotationsProvider() {
this(new JavaAnnotationConverter());
}
public JavaBasedCoreAnnotationsProvider(final JavaAnnotationConverter converter) {
super(converter, Immutable.class.getPackage().getName());
}
@Override
String getAlias() {
return ALIAS;
}
@Override
String getNameSpace() {
return NAMESPACE;
}
@Override
String getPath() {
return PATH;
}
@Override
URI getUri() throws URISyntaxException {
return new URI(
"https://raw.githubusercontent.com/oasis-tcs/odata-vocabularies/main/vocabularies/Org.OData.Core.V1.xml");// NOSONAR
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaBasedCapabilitiesAnnotationsProvider.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaBasedCapabilitiesAnnotationsProvider.java | package com.sap.olingo.jpa.metadata.odata.v4.provider;
import java.net.URI;
import java.net.URISyntaxException;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.FilterExpressionType;
public class JavaBasedCapabilitiesAnnotationsProvider extends JavaBasedODataAnnotationsProvider {
//
static final String NAMESPACE = "Org.OData.Capabilities.V1";
static final String ALIAS = "Capabilities";
static final String PATH = "vocabularies/Org.OData.Capabilities.V1.xml";
public JavaBasedCapabilitiesAnnotationsProvider() {
this(new JavaAnnotationConverter());
}
public JavaBasedCapabilitiesAnnotationsProvider(final JavaAnnotationConverter converter) {
super(converter, FilterExpressionType.class.getPackage().getName());
}
@Override
String getAlias() {
return ALIAS;
}
@Override
String getNameSpace() {
return NAMESPACE;
}
@Override
String getPath() {
return PATH;
}
@Override
URI getUri() throws URISyntaxException {
return new URI(
"https://raw.githubusercontent.com/oasis-tcs/odata-vocabularies/main/vocabularies/Org.OData.Capabilities.V1.xml");// NOSONAR
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaAnnotationConverter.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/provider/JavaAnnotationConverter.java | package com.sap.olingo.jpa.metadata.odata.v4.provider;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlComplexType;
import org.apache.olingo.commons.api.edm.provider.CsdlEnumType;
import org.apache.olingo.commons.api.edm.provider.CsdlNamed;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlTerm;
import org.apache.olingo.commons.api.edm.provider.CsdlTypeDefinition;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlNavigationPropertyPath;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyPath;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlPropertyValue;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlRecord;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.JPAReferences;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataAnnotatable;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataPathNotFoundException;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
class JavaAnnotationConverter {
private static final Log LOGGER = LogFactory.getLog(JavaAnnotationConverter.class);
static final String EDM_NAMESPACE = "Edm";
static final String IS_COLLECTION_TERM = "Collection";
static final String NULL = "null";
JavaAnnotationConverter() {
super();
}
Optional<CsdlAnnotation> convert(@Nonnull final JPAReferences references,
@Nonnull final Annotation annotation, @Nonnull final ODataAnnotatable annotatable) {
return Optional.ofNullable(annotation.annotationType().getAnnotation(Vocabulary.class))
.map(Vocabulary::alias)
.map(references::convertAlias)
.map(name -> new FullQualifiedName(name, annotation.annotationType().getSimpleName()))
.map(fqn -> references.getTerm(fqn).orElse(null))
.map(term -> asEdmAnnotation(references, annotation, term, annotatable));
}
private CsdlCollection asCollectionExpression(final JPAReferences references,
final AnnotationType propertyType, final ODataAnnotatable annotatable, final Object[] values) {
final var collection = new CsdlCollection();
final var collectionItems = collection.getItems();
final var fqn = propertyType.getFqn();
for (final Object item : splitCollectionValues(propertyType, values)) {
if (propertyType.isPrimitiveType())
collectionItems.add(asConstantExpression(propertyType, item));
else if (propertyType.isPathType()) {
final var expression = asPathExpression(annotatable, fqn, item);
if (expression != null)
collectionItems.add(asPathExpression(annotatable, fqn, item));
} else
collectionItems.add(asRecordExpression(references, (Annotation) item, propertyType, annotatable));
}
return collection;
}
private CsdlExpression asConstantExpression(final AnnotationType annotation, final Object value) {
if (value.getClass().isEnum())
return new CsdlConstantExpression(ConstantExpressionType.String, value.toString());
return new CsdlConstantExpression(asExpressionType(annotation), value.toString());
}
private CsdlPropertyValue asCsdlProperty(final CsdlProperty property, final CsdlExpression expression) {
final var propertyValue = new CsdlPropertyValue();
propertyValue.setValue(expression);
propertyValue.setProperty(property.getName());
return propertyValue;
}
private CsdlAnnotation asEdmAnnotation(final JPAReferences references,
final Annotation annotation, final CsdlTerm term, final ODataAnnotatable annotatable) {
final var alias = annotation.annotationType().getAnnotation(Vocabulary.class).alias();
final var namespace = references.convertAlias(alias);
final var edmAnnotation = new CsdlAnnotation();
final var annotationType = new AnnotationType(references, term);
edmAnnotation.setTerm(new FullQualifiedName(namespace, term.getName()).getFullQualifiedNameAsString());
edmAnnotation.setExpression(buildExpression(references, annotation, annotationType, annotatable));
return edmAnnotation;
}
private Optional<CsdlExpression> asEnumExpression(final Annotation annotation,
final AnnotationType propertyType, final String propertyName) {
final var propertyValue = getPropertyValue(annotation, propertyName);
return propertyValue.map(value -> asEnumExpression(propertyType, value));
}
private CsdlExpression asEnumExpression(final AnnotationType propertyType,
@Nonnull final Object propertyValue) {
final var enumType = propertyType.asEnumeration();
final var enumMember = enumType.getMember(propertyValue.toString());
return new CsdlConstantExpression(ConstantExpressionType.EnumMember,
enumMember == null ? NULL : enumMember.getName());
}
private ConstantExpressionType asExpressionType(final AnnotationType annotation) {
final var fqn = annotation.getBaseType() != null ? annotation.getBaseType() : annotation.getFqn();
return switch (EdmPrimitiveTypeKind.valueOfFQN(fqn)) {
case Boolean -> ConstantExpressionType.Bool;
case Int32 -> ConstantExpressionType.Int;
case String -> ConstantExpressionType.String;
default -> null;
};
}
@CheckForNull
private CsdlExpression asPathExpression(final ODataAnnotatable annotatable, final FullQualifiedName fqn,
final Object item) {
try {
return switch (fqn.getName()) {
case "PropertyPath" -> {
// http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part3-csdl/odata-v4.0-errata03-os-part3-csdl-complete.html#_Toc453752659
final var path = new CsdlPropertyPath();
path.setValue(annotatable.convertStringToPath(item.toString()).getPathAsString());
yield path;
}
case "NavigationPropertyPath" -> {
// http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part3-csdl/odata-v4.0-errata03-os-part3-csdl-complete.html#_Toc453752657
final var navigationPath = new CsdlNavigationPropertyPath();
navigationPath.setValue(annotatable.convertStringToNavigationPath(item.toString()).getPathAsString());
yield navigationPath;
}
default -> null;
};
} catch (final ODataPathNotFoundException e) {
LOGGER.error("Error orrured when trying to convert path '" + item.toString() + "' of " +
annotatable.getClass().getSimpleName(), e);
return null;
}
}
private CsdlExpression asRecordExpression(final JPAReferences references, final Annotation annotation,
final AnnotationType annotationType, final ODataAnnotatable annotatable) {
final var csdlRecord = new CsdlRecord();
final List<CsdlPropertyValue> recordProperties = new ArrayList<>();
csdlRecord.setType(annotationType.getFqn().getFullQualifiedNameAsString());
csdlRecord.setPropertyValues(recordProperties);
for (final CsdlProperty property : annotationType.asComplexType().getProperties()) {
final var propertyType = new AnnotationType(references, property);
if (propertyType.isCollection()) {
getPropertyValue(annotation, property.getName())
.map(Object[].class::cast)
.map(values -> asCollectionExpression(references, propertyType, annotatable, values))
.map(expression -> asCsdlProperty(property, expression))
.ifPresent(recordProperties::add);
} else if (propertyType.isEnumeration()) {
asEnumExpression(annotation, propertyType, property.getName())
.map(expression -> asCsdlProperty(property, expression))
.ifPresent(recordProperties::add);
} else if (propertyType.isPathType()) {
getPropertyValue(annotation, property.getName())
.map(value -> asPathExpression(annotatable, propertyType.getFqn(), value))
.filter(Objects::nonNull)
.map(expression -> asCsdlProperty(property, expression))
.ifPresent(recordProperties::add);
} else {
// A property may have a list of allowed values e.g. FilterRestrictions
// (https://github.com/oasis-tcs/odata-vocabularies/blob/main/vocabularies/Org.OData.Capabilities.V1.xml#L430)
// contains FilterExpressionRestrictionType, which contains AllowedExpressions of type FilterExpressionType. The
// later one is of type Validation.AllowedValues, which is a list of the allowed values. Such a list is
// converted into an enumeration, which has to be converted back into a String
getPropertyValue(annotation, property.getName())
.map(value -> asConstantExpression(propertyType, value))
.map(expression -> asCsdlProperty(property, expression))
.ifPresent(recordProperties::add);
}
}
return csdlRecord;
}
private CsdlExpression buildExpression(final JPAReferences references, final Annotation annotation,
final AnnotationType annotationType, final ODataAnnotatable annotatable) {
final var value = getPropertyValue(annotation, "value");
if (annotationType.isCollection) {
final var collection = new CsdlCollection();
if (value.isPresent()) {
for (final Object item : (Object[]) value.get()) {
collection.getItems().add(buildRowExpression(references, annotation, annotationType, annotatable, item));
}
}
return collection;
} else {
return buildRowExpression(references, annotation, annotationType, annotatable, value.orElse(null));
}
}
private CsdlExpression buildRowExpression(final JPAReferences references, final Annotation annotation,
final AnnotationType annotationType, final ODataAnnotatable annotatable, final Object value) {
if (annotationType.isComplexType()) {
return asRecordExpression(references, annotation, annotationType, annotatable);
} else if (annotationType.isEnumeration()) {
return asEnumExpression(annotationType, value);
} else {
return asConstantExpression(annotationType, value);
}
}
private String firstToLower(@Nonnull final String name) {
final var asArray = name.toCharArray();
asArray[0] = Character.toLowerCase(asArray[0]);
return String.valueOf(asArray);
}
private Optional<Object> getPropertyValue(final Annotation annotation, final String propertyName) {
try {
final var method = annotation.getClass().getMethod(firstToLower(propertyName));
return Optional.ofNullable(method.invoke(annotation));
} catch (final NoSuchMethodException unSupported) {
LOGGER.trace("Unsupported property of annotation: " + propertyName);
return Optional.empty();
} catch (SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e1) {
LOGGER.error("Not able to convert property: " + propertyName, e1);
return Optional.empty();
}
}
private List<Object> splitCollectionValues(final AnnotationType propertyType, final Object[] values) {
final List<Object> items = new ArrayList<>();
for (final Object value : values) {
if (propertyType.isComplexType()) {
items.add(value);
} else {
final var itemElements = value.toString().split(",");
items.addAll(Arrays.asList(itemElements));
}
}
return items;
}
private static class AnnotationType {
private final FullQualifiedName typeFqn;
private final Optional<? extends CsdlNamed> type;
private final boolean isCollection;
private AnnotationType(final JPAReferences references, final CsdlProperty property) {
this.typeFqn = new FullQualifiedName(property.getType());
this.isCollection = property.isCollection();
this.type = references.getType(typeFqn);
}
private AnnotationType(final JPAReferences references, final CsdlTerm term) {
this.typeFqn = determineTypeOfTerm(term);
this.isCollection = this.isCollectionType(term);
this.type = references.getType(typeFqn);
}
@Override
public String toString() {
return "AnnotationType [typeFqn=" + typeFqn + "]";
}
private CsdlComplexType asComplexType() {
return (CsdlComplexType) type.get();
}
private CsdlEnumType asEnumeration() {
return ((CsdlEnumType) type.get());
}
private FullQualifiedName determineTypeOfTerm(final CsdlTerm term) {
// E.g.: "Collection(Edm.String) or Capabilities.FilterRestrictionsType
if (isCollectionType(term))
return new FullQualifiedName(term.getType().split("\\(")[1].replace(")", ""));
return new FullQualifiedName(term.getType());
}
private FullQualifiedName getFqn() {
return typeFqn;
}
private FullQualifiedName getBaseType() {
return type
.filter(CsdlTypeDefinition.class::isInstance)
.map(CsdlTypeDefinition.class::cast)
.map(CsdlTypeDefinition::getUnderlyingType)
.map(FullQualifiedName::new)
.orElse(null);
}
private boolean isCollection() {
return isCollection;
}
private boolean isCollectionType(final CsdlTerm term) {
return term.getType().startsWith(IS_COLLECTION_TERM);
}
private boolean isComplexType() {
return type.isPresent() && type.get() instanceof CsdlComplexType;
}
private boolean isEnumeration() {
return type.isPresent() && type.get() instanceof CsdlEnumType;
}
private boolean isPathType() {
return EDM_NAMESPACE.equals(typeFqn.getNamespace())
&& ("PropertyPath".equals(typeFqn.getName())
|| "NavigationPropertyPath".equals(typeFqn.getName()));
}
private boolean isPrimitiveType() {
return (EDM_NAMESPACE.equals(typeFqn.getNamespace())
&& EdmPrimitiveTypeKind.getByName(typeFqn.getName()) != 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-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Immutable.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Immutable.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <i>Immutable</i>: <br>
* A value for this non-key property can be provided on insert and remains unchanged on update.
* <p>
*
* AppliesTo: Property
* @author Oliver Grande
*
*/
@Target(FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
@Vocabulary(alias = "Core", appliesTo = { Applicability.PROPERTY })
public @interface Immutable {
boolean value() default true;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Computed.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Computed.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <i>Computed</i>: <br>
* A value for this property is generated on both insert and update.
* <p>
*
* AppliesTo: Property
* @author Oliver Grande
*
*/
@Target(FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
@Vocabulary(alias = "Core", appliesTo = { Applicability.PROPERTY })
public @interface Computed {
boolean value() default true;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/ComputedDefaultValue.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/ComputedDefaultValue.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import static java.lang.annotation.ElementType.FIELD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <i>ComputedDefaultValue</i>: <br>
* A value for this property can be provided by the client on insert and update. If no value is provided on insert, a
* non-static default value is generated.
* <p>
*
* AppliesTo: Property
* @author Oliver Grande
*
*/
@Target(FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
@Vocabulary(alias = "Core", appliesTo = { Applicability.PROPERTY })
public @interface ComputedDefaultValue {
boolean value() default true;
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/GeneralProperty.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/GeneralProperty.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum GeneralProperty implements PropertyAccess {
VALUE("Value");
private final String property;
GeneralProperty(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Terms.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Terms.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.TermAccess;
public enum Terms implements TermAccess {
COMPUTED("Computed"),
COMPUTED_DEFAULT_VALUE("ComputedDefaultValue"),
IMMUTABLE("Immutable"),
EXAMPLE("Example");
private final String term;
Terms(final String term) {
this.term = term;
}
@Override
public String term() {
return term;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Example.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/Example.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.odata.v4.general.Vocabulary;
/**
* OData core annotation <i>Example</i>: <br>
* Example for an instance of the annotated model element. The value of Core.Example is a record/object containing the
* example value and/or annotation examples. <br>
* An example can have different flavors. It could be a PrimitiveExampleValue, a ComplexExampleValue, an
* EntityExampleValue or an ExternalExampleValue. Out of those only the last one is supported by this java annotation.
* <p>
* Example:<br>
* <code>
* description = "External example"
* externalValue = "https://services.odata.org/TripPinRESTierService/(S(5fjoyrzpnvzrrvmxzzq25i4q))/Me"
* </code>
* <p>
*
* AppliesTo: EntityType, Property, NavigationProperty
* @author Oliver Grande
*
*/
@Retention(RUNTIME)
@Target({ TYPE, FIELD })
@Vocabulary(alias = "Core", appliesTo = { Applicability.ENTITY_TYPE, Applicability.PROPERTY,
Applicability.NAVIGATION_PROPERTY })
public @interface Example {
/**
* Description of the example value
*/
String description() default "";
/**
* Url reference to the value in its literal format
*/
String externalValue();
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/GenaralProperty.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/GenaralProperty.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum GenaralProperty implements PropertyAccess {
VALUE("Value");
private final String property;
GenaralProperty(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/ExampleProperties.java | jpa/odata-jpa-odata-vocabularies/src/main/java/com/sap/olingo/jpa/metadata/odata/v4/core/terms/ExampleProperties.java | package com.sap.olingo.jpa.metadata.odata.v4.core.terms;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
public enum ExampleProperties implements PropertyAccess {
DESCRIPTION("Description"),
EXTERNAL_VALUE("ExternalValue");
private final String property;
ExampleProperties(final String property) {
this.property = property;
}
@Override
public String property() {
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/test/JPAODataBatchSequentialRequestGroupTest.java | jpa/odata-jpa-processor-parallel/src/test/JPAODataBatchSequentialRequestGroupTest.java | package com.sap.olingo.jpa.processor.core.api;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHandler;
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.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchException;
public class JPAODataBatchSequentialRequestGroupTest {
private JPAODataBatchSequentialRequestGroup cut;
private JPAODataBatchProcessor processor;
private ODataHandler odataHandler;
private JPAODataRequestContextAccess requestContext;
private JPAODataCRUDContextAccess serviceContext;
private OData odata;
private ServiceMetadata serviceMetadata;
private List<BatchRequestPart> groupElements;
@BeforeEach
public void setup() {
odata = mock(OData.class);
serviceMetadata = mock(ServiceMetadata.class);
serviceContext = mock(JPAODataCRUDContextAccess.class);
requestContext = mock(JPAODataRequestContextAccess.class);
odataHandler = mock(ODataHandler.class);
processor = mock(JPAODataBatchProcessor.class);
groupElements = new ArrayList<>();
processor.init(odata, serviceMetadata);
when(odata.createRawHandler(serviceMetadata)).thenReturn(odataHandler);
cut = new JPAODataBatchSequentialRequestGroup(processor, groupElements);
}
//final ODataHandler odataHandler = processor.odata.createRawHandler(processor.serviceMetadata);
//odataHandler.register(new JPAODataRequestProcessor(processor.serviceContext, processor.requestContext));
//handle(request.getRequests().get(0), false);
// response = oDataHandler.process(request);
@Test
public void testEmptyGroupsReturnEmptyResult() {
Assertions.assertTrue(cut.execute().isEmpty());
}
@Test
public void testOneGroupOneResult() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> get = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
get.add(request);
groupElements.add(part);
when(part.getRequests()).thenReturn(get);
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(1, act.size());
verify(odataHandler, times(1)).process(request);
}
@Test
public void testTwoGroupTwoResults() {
final ODataRequest request1 = buildPart();
final ODataRequest request2 = buildPart();
final ODataResponse part1 = mock(ODataResponse.class);
final ODataResponse part2 = mock(ODataResponse.class);
when(odataHandler.process(request1)).thenReturn(part1);
when(odataHandler.process(request2)).thenReturn(part2);
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(2, act.size());
verify(odataHandler, times(1)).process(request1);
verify(odataHandler, times(1)).process(request2);
Assertions.assertEquals(part1, act.get(0).getResponses().get(0));
Assertions.assertEquals(part2, act.get(1).getResponses().get(0));
}
@Test
public void testExceptionGetsRethrown() {
Assertions.assertThrows(ODataJPABatchException.class, () -> cut.execute());
}
private ODataRequest buildPart() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> get = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
get.add(request);
groupElements.add(part);
when(part.getRequests()).thenReturn(get);
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-parallel/src/test/java/com/sap/olingo/jpa/processor/test/util/IntegrationTestHelper.java | jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/test/util/IntegrationTestHelper.java | package com.sap.olingo.jpa.processor.test.util;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHttpHandler;
import org.mockito.Answers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sap.olingo.jpa.metadata.api.JPAEdmProvider;
import com.sap.olingo.jpa.processor.core.api.JPAODataApiVersionAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataBatchProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContext;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor;
import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor;
import com.sap.olingo.jpa.processor.core.processor.JPAODataInternalRequestContext;
import com.sap.olingo.jpa.processor.core.util.HttpRequestHeaderDouble;
import com.sap.olingo.jpa.processor.core.util.ServletInputStreamDouble;
public class IntegrationTestHelper {
public final HttpServletRequest req;
public final HttpServletResponse resp;
private static final String uriPrefix = "http://localhost:8080/Test/Olingo.svc/";
private static final String PUNIT_NAME = "com.sap.olingo.jpa";
private static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" };
private final JPAODataSessionContextAccess sessionContext;
private final JPAODataRequestContext customContext;
public IntegrationTestHelper(final EntityManagerFactory emf, final String urlPath, final StringBuilder requestBody)
throws IOException, ODataException {
final OData odata = OData.newInstance();
final EntityManager em = emf.createEntityManager();
final Map<String, List<String>> headers = Collections.emptyMap();
final JPAODataApiVersionAccess version = mock(JPAODataApiVersionAccess.class);
this.req = getRequestMock(uriPrefix + urlPath, requestBody, headers);
this.resp = getResponseMock();
this.customContext = mock(JPAODataRequestContext.class);
this.sessionContext = mock(JPAODataSessionContextAccess.class);
final JPAEdmProvider edmProvider = new JPAEdmProvider(PUNIT_NAME, emf, null, enumPackages);
when(version.getEdmProvider()).thenReturn(edmProvider);
when(sessionContext.getDatabaseProcessor()).thenReturn(new JPADefaultDatabaseProcessor());
when(sessionContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor());
when(sessionContext.getApiVersion(anyString())).thenReturn(version);
when(customContext.getEntityManager()).thenReturn(em);
when(customContext.getVersion()).thenReturn("V1");
final ODataHttpHandler handler = odata.createHandler(odata.createServiceMetadata(edmProvider,
new ArrayList<>()));
final JPAODataInternalRequestContext requestContext = new JPAODataInternalRequestContext(customContext,
sessionContext, odata);
handler.register(new JPAODataRequestProcessor(sessionContext, requestContext));
handler.register(new JPAODataBatchProcessor(sessionContext, requestContext));
handler.process(req, resp);
}
public List<String> getRawBatchResult() throws IOException {
final List<String> result = new ArrayList<>();
final InputStream in = asInputStream();
final BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;
while ((read = br.readLine()) != null) {
result.add(read);
}
br.close();
return result;
}
public int getBatchResultStatus(final int index) throws IOException {
final List<String> result = getRawBatchResult();
int count = 0;
for (final String resultLine : result) {
if (resultLine.contains("HTTP/1.1")) {
count += 1;
if (count == index) {
final String[] statusElements = resultLine.split(" ");
return Integer.parseInt(statusElements[1]);
}
}
}
return 0;
}
public InputStream asInputStream() throws IOException {
return new ResultStream((OutPutStream) resp.getOutputStream());
}
public JsonNode getBatchResult(final int index) throws IOException {
final List<String> result = getRawBatchResult();
int count = 0;
boolean found = false;
for (final String resultLine : result) {
if (resultLine.contains("HTTP/1.1")) {
count += 1;
if (count == index) {
found = true;
}
}
if (found && resultLine.startsWith("{")) {
final ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(resultLine);
}
}
return null;
}
public HttpServletRequest getRequestMock(final String uri, final StringBuilder body,
final Map<String, List<String>> headers) throws IOException {
final HttpRequestHeaderDouble reqHeader = new HttpRequestHeaderDouble();
final HttpServletRequest response = mock(HttpServletRequest.class);
final String[] uriParts = uri.split("\\?");
reqHeader.setHeaders(headers);
if (uri.contains("$batch")) {
when(response.getMethod()).thenReturn(HttpMethod.POST.toString());
reqHeader.setBatchRequest();
} else {
when(response.getMethod()).thenReturn(HttpMethod.GET.toString());
}
when(response.getInputStream()).thenReturn(new ServletInputStreamDouble(body));
when(response.getProtocol()).thenReturn("HTTP/1.1");
when(response.getServletPath()).thenReturn("/Olingo.svc");
when(response.getQueryString()).thenReturn((uriParts.length == 2) ? uriParts[1] : null);
when(response.getRequestURL()).thenReturn(new StringBuffer(uriParts[0]));
when(response.getHeaderNames()).thenReturn(reqHeader.getEnumerator());
when(response.getCharacterEncoding()).thenReturn("UTF8");
final Enumeration<String> headerEnumerator = reqHeader.getEnumerator();
while (headerEnumerator.hasMoreElements()) {
final String header = headerEnumerator.nextElement();
when(response.getHeaders(header)).thenReturn(reqHeader.get(header));
}
return response;
}
public HttpServletResponse getResponseMock() throws IOException {
final HttpServletResponse response = mock(HttpServletResponse.class, Answers.RETURNS_MOCKS);
when(response.getOutputStream()).thenReturn(new OutPutStream());
return response;
}
class OutPutStream extends ServletOutputStream {
List<Integer> buffer = new ArrayList<>();
@Override
public void write(final int b) throws IOException {
buffer.add(b);
}
public Iterator<Integer> getBuffer() {
return buffer.iterator();
}
public int getSize() {
return buffer.size();
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(final WriteListener writeListener) {
// Not needed
}
}
//
class ResultStream extends InputStream {
private final Iterator<Integer> bufferExcess;
public ResultStream(final OutPutStream buffer) {
super();
this.bufferExcess = buffer.getBuffer();
}
@Override
public int read() throws IOException {
if (bufferExcess.hasNext())
return bufferExcess.next();
return -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-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchAbstractRequestGroupTest.java | jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchAbstractRequestGroupTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataHandler;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Answers;
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.api.JPAServiceDebugger;
import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger.JPARuntimeMeasurement;
abstract class JPAODataBatchAbstractRequestGroupTest {
protected JPAODataParallelBatchProcessor processor;
protected ODataHandler odataHandler;
private JPAODataRequestContextAccess requestContext;
private JPAODataSessionContextAccess serviceContext;
private OData odata;
private ServiceMetadata serviceMetadata;
protected List<BatchRequestPart> groupElements;
private JPAServiceDebugger debugger;
private JPARuntimeMeasurement measurment;
@BeforeEach
void setup() {
debugger = mock(JPAServiceDebugger.class);
odata = mock(OData.class);
serviceMetadata = mock(ServiceMetadata.class);
serviceContext = mock(JPAODataSessionContextAccess.class);
requestContext = mock(JPAODataRequestContextAccess.class, withSettings().defaultAnswer(Answers.RETURNS_DEEP_STUBS));
odataHandler = mock(ODataHandler.class);
measurment = mock(JPARuntimeMeasurement.class);
processor = spy(new JPAODataParallelBatchProcessor(serviceContext, requestContext));
groupElements = new ArrayList<>();
processor.init(odata, serviceMetadata);
when(odata.createRawHandler(serviceMetadata)).thenReturn(odataHandler);
when(requestContext.getDebugger()).thenReturn(debugger);
when(debugger.newMeasurement(any(), any())).thenReturn(measurment);
}
protected ODataRequest buildPart() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> get = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
get.add(request);
groupElements.add(part);
when(part.getRequests()).thenReturn(get);
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-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataParallelBatchProcessorTest.java | jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataParallelBatchProcessorTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.RollbackException;
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.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.BatchRequestPart;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
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.JPAODataSessionContextAccess;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory;
import com.sap.olingo.jpa.processor.core.api.JPAODataTransactionFactory.JPAODataTransaction;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPATransactionException;
class JPAODataParallelBatchProcessorTest {
private JPAODataParallelBatchProcessor cut;
@Mock
private EntityManager em;
@Mock
private JPAODataTransaction transaction;
@Mock
private OData odata;
@Mock
private ServiceMetadata serviceMetadata;
@Mock
private BatchFacade facade;
@Mock
private ODataRequest request;
@Mock
private ODataResponse response;
@Mock
private RollbackException e;
@Mock
private JPAODataSessionContextAccess context;
@Mock
private JPACUDRequestHandler cudHandler;
@Mock
private JPAODataRequestContextAccess requestContext;
@Mock
private JPAODataTransactionFactory factory;
@Mock
private JPAODataSessionContextAccess sessionContext;
@BeforeEach
void setup() throws ODataJPATransactionException {
MockitoAnnotations.openMocks(this);
when(requestContext.getEntityManager()).thenReturn(em);
when(requestContext.getCUDRequestHandler()).thenReturn(cudHandler);
when(requestContext.getTransactionFactory()).thenReturn(factory);
when(factory.createTransaction()).thenReturn(transaction);
cut = new JPAODataParallelBatchProcessor(sessionContext, requestContext);
cut.init(odata, serviceMetadata);
when(requestContext.getDebugger()).thenReturn(new JPAEmptyDebugger());
}
@Test
void testBuildGroupsReturnsEmptyListOnEmptyInput() throws ODataJPABatchException {
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(Collections.emptyList());
Assertions.assertNotNull(act);
Assertions.assertTrue(act.isEmpty());
}
@Test
void testBuildGroupsReturnsOneSequentialGroupOnOnePart() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(1, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchSequentialRequestGroup);
}
@Test
void testBuildGroupsThrowsExceptionOnNonChangeSetWithMultipleEntries() {
final List<BatchRequestPart> requests = buildParts(buildGet(false, mock(ODataRequest.class)));
final ODataJPABatchException act = Assertions.assertThrows(ODataJPABatchException.class, () -> cut.buildGroups(
requests));
Assertions.assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), act.getStatusCode());
Assertions.assertNotNull(act.getMessage());
Assertions.assertFalse(act.getMessage().contains("No message text found"));
}
@Test
void testBuildGroupsAcceptsChangeSetWithMultipleEntries() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(true, mock(ODataRequest.class)));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(1, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchSequentialRequestGroup);
}
@Test
void testBuildGroupsReturnsOneParallelForTwoGets() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(false), buildGet(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(1, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchParallelRequestGroup);
}
@Test
void testBuildGroupsReturnsSeqSeqForGetPost() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(false), buildPost(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(2, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchSequentialRequestGroup);
Assertions.assertTrue(act.get(1) instanceof JPAODataBatchSequentialRequestGroup);
}
@Test
void testBuildGroupsReturnsParaSeqForGetGetPost() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(false), buildGet(false), buildPost(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(2, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchParallelRequestGroup);
Assertions.assertTrue(act.get(1) instanceof JPAODataBatchSequentialRequestGroup);
}
@Test
void testBuildGroupsReturnsSeqParaForPatchGetGet() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildPatch(false), buildGet(false), buildGet(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(2, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchSequentialRequestGroup);
Assertions.assertTrue(act.get(1) instanceof JPAODataBatchParallelRequestGroup);
}
@Test
void testBuildGroupsReturnsParaSeqParaForGetGetPatchGetGet() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(false), buildGet(false), buildPatch(false), buildGet(
false), buildGet(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(3, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchParallelRequestGroup);
Assertions.assertTrue(act.get(1) instanceof JPAODataBatchSequentialRequestGroup);
Assertions.assertTrue(act.get(2) instanceof JPAODataBatchParallelRequestGroup);
}
@Test
void testBuildGroupsReturnsParaSeqForGetGetChangeSet() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(false), buildGet(false), buildGet(true));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(2, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchParallelRequestGroup);
Assertions.assertTrue(act.get(1) instanceof JPAODataBatchSequentialRequestGroup);
}
@Test
void testBuildGroupsReturnsParaSeqForChangeSetGetGet() throws ODataJPABatchException {
final List<BatchRequestPart> requests = buildParts(buildGet(true), buildGet(false), buildGet(false));
final List<JPAODataBatchRequestGroup> act = cut.buildGroups(requests);
Assertions.assertNotNull(act);
Assertions.assertEquals(2, act.size());
Assertions.assertTrue(act.get(0) instanceof JPAODataBatchSequentialRequestGroup);
Assertions.assertTrue(act.get(1) instanceof JPAODataBatchParallelRequestGroup);
}
private BatchRequestPart buildGet(final boolean isChangeSet, final ODataRequest... addRequest) {
return buildPart(HttpMethod.GET, isChangeSet, addRequest);
}
private BatchRequestPart buildPost(final boolean isChangeSet, final ODataRequest... addRequest) {
return buildPart(HttpMethod.POST, isChangeSet, addRequest);
}
private BatchRequestPart buildPatch(final boolean isChangeSet, final ODataRequest... addRequest) {
return buildPart(HttpMethod.PATCH, isChangeSet, addRequest);
}
private BatchRequestPart buildPart(final HttpMethod method, final boolean isChangeSet,
final ODataRequest... addRequest) {
final BatchRequestPart post = mock(BatchRequestPart.class);
final List<ODataRequest> requestParts = new ArrayList<>();
final ODataRequest getPart = mock(ODataRequest.class);
when(post.getRequests()).thenReturn(requestParts);
when(post.isChangeSet()).thenReturn(isChangeSet);
when(getPart.getMethod()).thenReturn(method);
requestParts.add(getPart);
requestParts.addAll(Arrays.asList(addRequest));
return post;
}
private List<BatchRequestPart> buildParts(final BatchRequestPart... get) {
final List<BatchRequestPart> requests = new ArrayList<>();
requests.addAll(Arrays.asList(get));
return requests;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchParallelRequestGroupTest.java | jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchParallelRequestGroupTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchRuntimeException;
class JPAODataBatchParallelRequestGroupTest extends JPAODataBatchAbstractRequestGroupTest {
private JPAODataBatchParallelRequestGroup cut;
@Override
@BeforeEach
void setup() {
super.setup();
cut = new JPAODataBatchParallelRequestGroup(processor, groupElements);
}
@Test
void testEmptyGroupsReturnEmptyResult() {
Assertions.assertTrue(cut.execute().isEmpty());
}
@Test
void testOneGroupOneResult() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> get = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
get.add(request);
groupElements.add(part);
when(part.getRequests()).thenReturn(get);
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(1, act.size());
verify(odataHandler, times(1)).process(request);
}
@Test
void testTwoPartsFirstSlower() {
final ODataRequest request1 = buildPart();
final ODataRequest request2 = buildPart();
final ODataResponse part1 = mock(ODataResponse.class);
final ODataResponse part2 = mock(ODataResponse.class);
when(odataHandler.process(request1)).thenAnswer(new AnswerLate<>(100, part1));
when(odataHandler.process(request2)).thenAnswer(new AnswerLate<>(10, part2));
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(2, act.size());
verify(odataHandler, times(1)).process(request1);
verify(odataHandler, times(1)).process(request2);
Assertions.assertEquals(part1, act.get(0).getResponses().get(0));
Assertions.assertEquals(part2, act.get(1).getResponses().get(0));
}
@Test
void testTwoPartsSecondSlower() {
final ODataRequest request1 = buildPart();
final ODataRequest request2 = buildPart();
final ODataResponse part1 = mock(ODataResponse.class);
final ODataResponse part2 = mock(ODataResponse.class);
when(odataHandler.process(request1)).thenAnswer(new AnswerLate<>(10, part1));
when(odataHandler.process(request2)).thenAnswer(new AnswerLate<>(100, part2));
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(2, act.size());
verify(odataHandler, times(1)).process(request1);
verify(odataHandler, times(1)).process(request2);
Assertions.assertEquals(part1, act.get(0).getResponses().get(0));
Assertions.assertEquals(part2, act.get(1).getResponses().get(0));
}
@Test
void testThreePartsSecondSlower() {
final ODataRequest request1 = buildPart();
final ODataRequest request2 = buildPart();
final ODataRequest request3 = buildPart();
final ODataResponse part1 = mock(ODataResponse.class);
final ODataResponse part2 = mock(ODataResponse.class);
final ODataResponse part3 = mock(ODataResponse.class);
when(odataHandler.process(request1)).thenAnswer(new AnswerLate<>(10, part1));
when(odataHandler.process(request2)).thenAnswer(new AnswerLate<>(100, part2));
when(odataHandler.process(request3)).thenAnswer(new AnswerLate<>(50, part3));
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(3, act.size());
Assertions.assertEquals(part1, act.get(0).getResponses().get(0));
Assertions.assertEquals(part2, act.get(1).getResponses().get(0));
Assertions.assertEquals(part3, act.get(2).getResponses().get(0));
}
@Test
void testExecuteRethrowsException() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> post = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
final ODataResponse response = mock(ODataResponse.class);
post.add(request);
groupElements.add(part);
when(request.getRawODataPath()).thenReturn("Organizations('3')");
when(request.getRawBaseUri()).thenReturn("Organizations('3')");
when(request.getMethod()).thenReturn(HttpMethod.POST);
when(part.getRequests()).thenReturn(post);
when(part.isChangeSet()).thenReturn(true);
when(response.getHeader(HttpHeader.LOCATION)).thenReturn("Hallo");
when(odataHandler.process(request)).thenReturn(response);
Assertions.assertThrows(ODataJPABatchRuntimeException.class, cut::execute);
}
private static class AnswerLate<T> implements Answer<T> {
private final int millisDelay;
private final T response;
public AnswerLate(final int millisDelay, final T response) {
this.millisDelay = millisDelay;
this.response = response;
}
@Override
public T answer(final InvocationOnMock invocation) throws Throwable {
Thread.sleep(millisDelay); // NOSONAR
return response;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchSequentialRequestGroupTest.java | jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchSequentialRequestGroupTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpMethod;
import org.apache.olingo.server.api.ODataRequest;
import org.apache.olingo.server.api.ODataResponse;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchRuntimeException;
class JPAODataBatchSequentialRequestGroupTest extends JPAODataBatchAbstractRequestGroupTest {
private JPAODataBatchSequentialRequestGroup cut;
@Override
@BeforeEach
void setup() {
super.setup();
cut = new JPAODataBatchSequentialRequestGroup(processor, groupElements);
}
@Test
void testEmptyGroupsReturnEmptyResult() {
Assertions.assertTrue(cut.execute().isEmpty());
}
@Test
void testOneGroupOneResult() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> get = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
get.add(request);
groupElements.add(part);
when(part.getRequests()).thenReturn(get);
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(1, act.size());
verify(odataHandler, times(1)).process(request);
}
@Test
void testTwoGroupTwoResults() {
final ODataRequest request1 = buildPart();
final ODataRequest request2 = buildPart();
final ODataResponse part1 = mock(ODataResponse.class);
final ODataResponse part2 = mock(ODataResponse.class);
when(odataHandler.process(request1)).thenReturn(part1);
when(odataHandler.process(request2)).thenReturn(part2);
final List<ODataResponsePart> act = cut.execute();
Assertions.assertEquals(2, act.size());
verify(odataHandler, times(1)).process(request1);
verify(odataHandler, times(1)).process(request2);
Assertions.assertEquals(part1, act.get(0).getResponses().get(0));
Assertions.assertEquals(part2, act.get(1).getResponses().get(0));
}
@Test
void testExecuteRethrowsException() {
final BatchRequestPart part = mock(BatchRequestPart.class);
final List<ODataRequest> post = new ArrayList<>(1);
final ODataRequest request = mock(ODataRequest.class);
final ODataResponse response = mock(ODataResponse.class);
post.add(request);
groupElements.add(part);
when(request.getRawODataPath()).thenReturn("Organizations('3')");
when(request.getRawBaseUri()).thenReturn("Organizations('3')");
when(request.getMethod()).thenReturn(HttpMethod.POST);
when(part.getRequests()).thenReturn(post);
when(part.isChangeSet()).thenReturn(true);
when(response.getHeader(HttpHeader.LOCATION)).thenReturn("Hallo");
when(odataHandler.process(request)).thenReturn(response);
Assertions.assertThrows(ODataJPABatchRuntimeException.class, cut::execute);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataParallelBatchProcessorIntegrationTest.java | jpa/odata-jpa-processor-parallel/src/test/java/com/sap/olingo/jpa/processor/core/processor/JPAODataParallelBatchProcessorIntegrationTest.java | package com.sap.olingo.jpa.processor.core.processor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.util.List;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
import com.sap.olingo.jpa.processor.test.util.IntegrationTestHelper;
class JPAODataParallelBatchProcessorIntegrationTest {
private static final String PUNIT_NAME = "com.sap.olingo.jpa";
private static EntityManagerFactory emf;
private static DataSource ds;
@BeforeAll
static void setupClass() {
ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_H2);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds);
}
@Test // Response
void testOneGetRequestGetResponse() throws IOException, ODataException {
final StringBuilder requestBody = createBodyOneGet();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody);
final List<String> act = helper.getRawBatchResult();
assertNotNull(act);
}
@Test
void testOneGetRequestCheckStatus() throws IOException, ODataException {
final StringBuilder requestBody = createBodyOneGet();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody);
assertEquals(200, helper.getBatchResultStatus(1));
}
@Test
void testOneGetRequestCheckValue() throws IOException, ODataException {
final StringBuilder requestBody = createBodyOneGet();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody);
assertEquals(200, helper.getBatchResultStatus(1));
final JsonNode value = helper.getBatchResult(1);
assertEquals("3", value.get("ID").asText());
}
@Test
void testTwoGetRequestSecondFailCheckStatus() throws IOException, ODataException {
final StringBuilder requestBody = createBodyTwoGetOneFail();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody);
assertEquals(404, helper.getBatchResultStatus(2));
}
@Test
void testTwoGetRequestCheckValue() throws IOException, ODataException {
final StringBuilder requestBody = createBodyTwoGet();
final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody);
JsonNode value = helper.getBatchResult(1);
System.out.println(value);
assertEquals(200, helper.getBatchResultStatus(1));
assertNotNull(value.get("ID"));
assertEquals("3", value.get("ID").asText());
value = helper.getBatchResult(2);
System.out.println(value);
assertEquals(200, helper.getBatchResultStatus(2));
assertNotNull(value.get("ID"));
assertEquals("5", value.get("ID").asText());
}
private StringBuilder createBodyTwoGetOneFail() {
final StringBuilder requestBody = new StringBuilder("--abc123\r\n");
requestBody.append("Content-Type: application/http\r\n");
requestBody.append("Content-Transfer-Encoding: binary\r\n");
requestBody.append("\r\n");
requestBody.append("GET Organizations('3') HTTP/1.1\r\n");
requestBody.append("Content-Type: application/json\r\n");
requestBody.append("\r\n");
requestBody.append("\r\n");
requestBody.append("--abc123\r\n");
requestBody.append("Content-Type: application/http\r\n");
requestBody.append("Content-Transfer-Encoding: binary\r\n");
requestBody.append("\r\n");
requestBody.append("GET AdministrativeDivision HTTP/1.1\r\n");
requestBody.append("Content-Type: application/json\r\n");
requestBody.append("\r\n");
requestBody.append("\r\n");
requestBody.append("--abc123--");
return requestBody;
}
private StringBuilder createBodyTwoGet() {
final StringBuilder requestBody = new StringBuilder("--abc123\r\n");
requestBody.append("Content-Type: application/http\r\n");
requestBody.append("Content-Transfer-Encoding: binary\r\n");
requestBody.append("\r\n");
requestBody.append("GET Organizations('3') HTTP/1.1\r\n");
requestBody.append("Content-Type: application/json\r\n");
requestBody.append("\r\n");
requestBody.append("\r\n");
requestBody.append("--abc123\r\n");
requestBody.append("Content-Type: application/http\r\n");
requestBody.append("Content-Transfer-Encoding: binary\r\n");
requestBody.append("\r\n");
requestBody.append("GET Organizations('5') HTTP/1.1\r\n");
requestBody.append("Content-Type: application/json\r\n");
requestBody.append("\r\n");
requestBody.append("\r\n");
requestBody.append("--abc123--");
return requestBody;
}
private StringBuilder createBodyOneGet() {
final StringBuilder requestBody = new StringBuilder("--abc123\r\n");
requestBody.append("Content-Type: application/http\r\n");
requestBody.append("Content-Transfer-Encoding: binary\r\n");
requestBody.append("\r\n");
requestBody.append("GET Organizations('3') HTTP/1.1\r\n");
requestBody.append("Content-Type: application/json\r\n");
requestBody.append("\r\n");
requestBody.append("\r\n");
requestBody.append("--abc123--");
return requestBody;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchSequentialRequestGroup.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchSequentialRequestGroup.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.List;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataHandler;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.batch.BatchFacade;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.apache.olingo.server.core.batchhandler.BatchFacadeImpl;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchRuntimeException;
public class JPAODataBatchSequentialRequestGroup implements JPAODataBatchRequestGroup {
private final JPAODataParallelBatchProcessor processor;
private final List<BatchRequestPart> groupElements;
public JPAODataBatchSequentialRequestGroup(final JPAODataParallelBatchProcessor processor,
final List<BatchRequestPart> groupElements) {
this.groupElements = groupElements;
this.processor = processor;
}
@Override
public List<ODataResponsePart> execute() {
final BatchFacade facade = buildFacade();
return groupElements.stream()
.map(part -> executePart(facade, part))
.toList();
}
private ODataResponsePart executePart(final BatchFacade facade, final BatchRequestPart part) {
try {
return facade.handleBatchRequest(part);
} catch (ODataApplicationException | ODataLibraryException e) {
throw new ODataJPABatchRuntimeException(e);
}
}
private BatchFacade buildFacade() {
final ODataHandler odataHandler = processor.getOdata().createRawHandler(processor.getServiceMetadata());
odataHandler.register(new JPAODataRequestProcessor(processor.getServiceContext(), processor.getRequestContext()));
return new BatchFacadeImpl(odataHandler, processor, true);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchParallelRequestGroup.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchParallelRequestGroup.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataHandler;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.batch.BatchFacade;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import org.apache.olingo.server.core.batchhandler.BatchFacadeImpl;
import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchRuntimeException;
class JPAODataBatchParallelRequestGroup implements JPAODataBatchRequestGroup {
private final List<BatchRequestPart> requestParts;
private final JPAODataParallelBatchProcessor processor;
JPAODataBatchParallelRequestGroup(final JPAODataParallelBatchProcessor processor,
final List<BatchRequestPart> requestParts) {
super();
this.requestParts = requestParts;
this.processor = processor;
}
@Override
public List<ODataResponsePart> execute() {
try {
processor.getRequestContext().getDebugger().debug(this, "Number of groups elements : %d", requestParts.size());
final List<CompletableFuture<ODataResponsePart>> requests = requestParts.stream()
.map(part -> startBatchPart(buildFacade(), part))
.toList();
return CompletableFuture.allOf(requests.toArray(new CompletableFuture[requests.size()]))
.thenApply(dummy -> requests.stream()
.map(CompletableFuture::join)
.toList()).join();
} catch (final RuntimeException e) {
// startBatchPart throws an runtime exception that wraps the original exception. This runtime exception gets is
// wrapped into an CompletionException. The original exception has to be re-wrapped, so the caller can handle it.
throw new ODataJPABatchRuntimeException((ODataException) e.getCause().getCause());
}
}
private BatchFacade buildFacade() {
final ODataHandler odataHandler = processor.getOdata().createRawHandler(processor.getServiceMetadata());
odataHandler.register(new JPAODataRequestProcessor(processor.getServiceContext(), processor.getRequestContext()));
return new BatchFacadeImpl(odataHandler, processor, true);
}
private CompletableFuture<ODataResponsePart> startBatchPart(final BatchFacade facade,
final BatchRequestPart requestPart) {
return CompletableFuture.supplyAsync(() -> {
try {
return facade.handleBatchRequest(requestPart);
} catch (ODataApplicationException | ODataLibraryException e) {
throw new ODataJPABatchRuntimeException(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-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataParallelBatchProcessor.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataParallelBatchProcessor.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
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.ServiceMetadata;
import org.apache.olingo.server.api.batch.BatchFacade;
import org.apache.olingo.server.api.deserializer.batch.BatchRequestPart;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import com.sap.olingo.jpa.processor.core.api.JPAODataBatchProcessor;
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.ODataJPABatchException;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchRuntimeException;
/**
* Process parts of a batch request in parallel. This is possible for GET requests until the first request with side
* effects comes. In case a request with side effect is followed by a set of request without side effect, they are
* processed in
* parallel again.
* <p>
* Please note that this is, according to the OData specification,only allowed:
* <ol>
* <li>In case the client sends an continue-on-error=true</li>
* <li>It is guaranteed that the GET do not fail
* </ol>
* @author Oliver Grande
* Created: 27.02.2020
*/
public class JPAODataParallelBatchProcessor extends JPAODataBatchProcessor {
public JPAODataParallelBatchProcessor(final JPAODataSessionContextAccess serviceContext,
final JPAODataRequestContextAccess requestContext) {
super(serviceContext, requestContext);
}
@Override
protected List<ODataResponsePart> executeBatchParts(final BatchFacade facade,
final List<BatchRequestPart> requestParts, final boolean continueOnError) throws ODataApplicationException,
ODataLibraryException {
try {
return buildGroups(requestParts).stream()
.map(JPAODataBatchRequestGroup::execute)
.flatMap(List::stream)
.toList();
} catch (final ODataJPABatchRuntimeException e) {
throw new ODataJPABatchException(e);
}
}
List<JPAODataBatchRequestGroup> buildGroups(@Nonnull final List<BatchRequestPart> requestParts)
throws ODataJPABatchException {
if (requestParts.isEmpty())
return Collections.emptyList();
final List<JPAODataBatchRequestGroup> groups = new ArrayList<>();
Boolean isGetGroup = null;
List<BatchRequestPart> groupElements = new ArrayList<>();
for (final BatchRequestPart part : requestParts) {
checkPartConsistency(part);
if (isGetGroup == null) {
isGetGroup = !part.isChangeSet() && isGetRequest(part);
} else if (Boolean.TRUE.equals(isGetGroup) && (!isGetRequest(part) || part.isChangeSet())) {
if (groupElements.size() == 1)
groups.add(new JPAODataBatchSequentialRequestGroup(this, groupElements));
else
groups.add(new JPAODataBatchParallelRequestGroup(this, groupElements));
groupElements = new ArrayList<>();
isGetGroup = Boolean.FALSE;
} else if (Boolean.FALSE.equals(isGetGroup) && isGetRequest(part)) {
groups.add(new JPAODataBatchSequentialRequestGroup(this, groupElements));
groupElements = new ArrayList<>();
isGetGroup = Boolean.TRUE;
}
groupElements.add(part);
}
addLastGroup(groups, isGetGroup, groupElements);
requestContext.getDebugger().debug(this, "Number of groups build: %d", groups.size());
return groups;
}
OData getOdata() {
return odata;
}
JPAODataRequestContextAccess getRequestContext() {
return requestContext;
}
JPAODataSessionContextAccess getServiceContext() {
return serviceContext;
}
ServiceMetadata getServiceMetadata() {
return serviceMetadata;
}
private void addLastGroup(final List<JPAODataBatchRequestGroup> groups, final Boolean isGetGroup,
final List<BatchRequestPart> groupElements) {
if (Boolean.FALSE.equals(isGetGroup) || groupElements.size() == 1)
groups.add(new JPAODataBatchSequentialRequestGroup(this, groupElements));
else
groups.add(new JPAODataBatchParallelRequestGroup(this, groupElements));
}
private boolean isGetRequest(final BatchRequestPart part) {
return part.getRequests().get(0).getMethod() == HttpMethod.GET;
}
private void checkPartConsistency(final BatchRequestPart part) throws ODataJPABatchException {
if (part.getRequests().size() > 1 && !part.isChangeSet())
throw new ODataJPABatchException(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-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchRequestGroup.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/processor/JPAODataBatchRequestGroup.java | package com.sap.olingo.jpa.processor.core.processor;
import java.util.List;
import org.apache.olingo.server.api.deserializer.batch.ODataResponsePart;
import com.sap.olingo.jpa.processor.core.exception.ODataJPABatchRuntimeException;
public interface JPAODataBatchRequestGroup {
/**
*
* @return
* @throws ODataJPABatchRuntimeException
*/
List<ODataResponsePart> execute();
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPABatchException.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPABatchException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.http.HttpStatusCode;
public class ODataJPABatchException extends ODataJPAProcessException { // NOSONAR
/**
*
*/
private static final long serialVersionUID = 8492368933922574285L;
private static final String BUNDLE_NAME = "batch-parallel-exceptions-i18n";
private static final String MESSAGE_KEY = "UNSUPPORTED_BATCH_PARTS";
public ODataJPABatchException(final HttpStatusCode statusCode) {
super(MESSAGE_KEY, statusCode);
}
public ODataJPABatchException(final ODataJPABatchRuntimeException e) {
super(e.getCause(), HttpStatusCode.INTERNAL_SERVER_ERROR);
}
@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-parallel/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPABatchRuntimeException.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/exception/ODataJPABatchRuntimeException.java | package com.sap.olingo.jpa.processor.core.exception;
import org.apache.olingo.commons.api.ex.ODataException;
public class ODataJPABatchRuntimeException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -4042442300828284445L;
public ODataJPABatchRuntimeException(ODataException e) {
super(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-parallel/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataParallelBatchProcessorFactory.java | jpa/odata-jpa-processor-parallel/src/main/java/com/sap/olingo/jpa/processor/core/api/JPAODataParallelBatchProcessorFactory.java | package com.sap.olingo.jpa.processor.core.api;
import javax.annotation.Nonnull;
import com.sap.olingo.jpa.processor.core.processor.JPAODataParallelBatchProcessor;
public class JPAODataParallelBatchProcessorFactory implements
JPAODataBatchProcessorFactory<JPAODataParallelBatchProcessor> {
@Override
public JPAODataParallelBatchProcessor getBatchProcessor(@Nonnull final JPAODataSessionContextAccess serviceContext,
@Nonnull final JPAODataRequestContextAccess requestContext) {
return new JPAODataParallelBatchProcessor(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-metadata/src/test/java/com/sap/olingo/jpa/metadata/api/JPAUserGroupRestrictableTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/api/JPAUserGroupRestrictableTest.java | package com.sap.olingo.jpa.metadata.api;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAUserGroupRestrictable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class JPAUserGroupRestrictableTest {
private JPAUserGroupRestrictable cut;
@BeforeEach
void setup() {
cut = spy(JPAUserGroupRestrictable.class);
}
@Test
void testIsAccessibleForIsTrueIfNotProtected() throws ODataJPAModelException {
when(cut.getUserGroups()).thenReturn(List.of());
assertTrue(cut.isAccessibleFor(List.of("Company")));
assertTrue(cut.isAccessibleFor(List.of()));
}
@Test
void testIsAccessibleForIsTrueIfProtected() throws ODataJPAModelException {
when(cut.getUserGroups()).thenReturn(List.of("Company"));
assertTrue(cut.isAccessibleFor(List.of("Company")));
}
@Test
void testIsAccessibleForIsTrueIfProtectedInList() throws ODataJPAModelException {
when(cut.getUserGroups()).thenReturn(List.of("Company", "Enterprise"));
assertTrue(cut.isAccessibleFor(List.of("Company")));
}
@Test
void testIsAccessibleForIsTrueIfProtectedInListOneMatch() throws ODataJPAModelException {
when(cut.getUserGroups()).thenReturn(List.of("Company", "Enterprise"));
assertTrue(cut.isAccessibleFor(List.of("Person", "Company")));
}
@Test
void testIsAccessibleForIsFalseIfGroupsNotEq() throws ODataJPAModelException {
when(cut.getUserGroups()).thenReturn(List.of("Company"));
assertFalse(cut.isAccessibleFor(List.of("Person")));
}
@Test
void testIsAccessibleForIsFalseIfGroupsNotInList() throws ODataJPAModelException {
when(cut.getUserGroups()).thenReturn(List.of("Company", "Enterprise"));
assertFalse(cut.isAccessibleFor(List.of("Person", "Employee")));
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/api/JPAEdmProviderTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/api/JPAEdmProviderTest.java | /**
*
*/
package com.sap.olingo.jpa.metadata.api;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
import java.util.List;
import javax.sql.DataSource;
import jakarta.persistence.EntityManagerFactory;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlAction;
import org.apache.olingo.commons.api.edm.provider.CsdlActionImport;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotations;
import org.apache.olingo.commons.api.edm.provider.CsdlComplexType;
import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer;
import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainerInfo;
import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet;
import org.apache.olingo.commons.api.edm.provider.CsdlEntityType;
import org.apache.olingo.commons.api.edm.provider.CsdlEnumType;
import org.apache.olingo.commons.api.edm.provider.CsdlFunction;
import org.apache.olingo.commons.api.edm.provider.CsdlFunctionImport;
import org.apache.olingo.commons.api.edm.provider.CsdlSchema;
import org.apache.olingo.commons.api.edm.provider.CsdlSingleton;
import org.apache.olingo.commons.api.edm.provider.CsdlTerm;
import org.apache.olingo.commons.api.edm.provider.CsdlTypeDefinition;
import org.apache.olingo.commons.api.ex.ODataException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList.IntermediateReferenceAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.CustomJPANameBuilder;
import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPADefaultEdmNameBuilder;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
/**
* @author Oliver Grande
* Created: 10.02.2020
*
*/
class JPAEdmProviderTest {
private static final String PUNIT_NAME = "com.sap.olingo.jpa";
private static final String ERROR_PUNIT = "error";
private static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" };
private static EntityManagerFactory emf;
private static DataSource dataSource;
private JPAEdmProvider cut;
private JPAEdmMetadataPostProcessor postProcessor;
@BeforeAll
static void setupClass() {
dataSource = DataSourceHelper.createDataSource(DataSourceHelper.DB_H2);
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, dataSource);
}
@BeforeEach
void setup() throws ODataException {
cut = new JPAEdmProvider(PUNIT_NAME, emf, null, enumPackages);
}
@Test
void checkReturnsDefaultNamerBuilderIfNotProvided() {
assertTrue(cut.getEdmNameBuilder() instanceof JPADefaultEdmNameBuilder);
}
@Test
void checkReturnsReferencesFromServiceDocument() {
assertEquals(cut.getServiceDocument().getReferences(), cut.getReferences());
}
@Test
void checkThrowsExceptionOnMissingNamespace() {
assertThrows(NullPointerException.class, () -> new JPAEdmProvider(null, emf, null, enumPackages));
}
@Test
void checkThrowsExceptionOnMissingEmf() {
final EntityManagerFactory nullFactory = null;
assertThrows(NullPointerException.class, () -> new JPAEdmProvider("Willi", nullFactory, null, enumPackages));
}
@Test
void checkGetSchemas() throws ODataException {
final JPAEdmNameBuilder nameBuilder = new CustomJPANameBuilder();
cut = new JPAEdmProvider(emf.getMetamodel(), null, null, nameBuilder, Collections.emptyList());
final JPAServiceDocument act = cut.getServiceDocument();
assertNotNull(act);
assertEquals(nameBuilder, act.getNameBuilder());
}
@Test
void checkGetSchemasReturnsOneSchema() throws ODataException {
final List<CsdlSchema> act = cut.getSchemas();
assertEquals(1, act.size());
assertNotNull(act.get(0));
assertEquals(PUNIT_NAME, act.get(0).getNamespace());
}
@Test
void checkGetEnumReturnsNullOnUnknown() throws ODataException {
final CsdlEnumType act = cut.getEnumType(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkGetEnumReturnsKnownEnum() throws ODataException {
final CsdlEnumType act = cut.getEnumType(new FullQualifiedName(PUNIT_NAME, "AccessRights"));
assertNotNull(act);
assertTrue(act.isFlags());
}
@Test
void checkGetComplexTypeReturnsNullOnUnknown() throws ODataException {
final CsdlComplexType act = cut.getComplexType(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkGetComplexTypeReturnsKnownEnum() throws ODataException {
final CsdlComplexType act = cut.getComplexType(new FullQualifiedName(PUNIT_NAME, "PostalAddressData"));
assertNotNull(act);
assertFalse(act.isAbstract());
}
@Test
void checkGetEntityContainerReturnsContainer() throws ODataException {
final CsdlEntityContainer act = cut.getEntityContainer();
assertNotNull(act);
assertEquals(cut.getServiceDocument().getNameBuilder().buildContainerName(), act.getName());
}
@Test
void checkGetEntityContainerInfoReturnsNullOnUnknown() throws ODataException {
final CsdlEntityContainerInfo act = cut.getEntityContainerInfo(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkEntityContainerInfoReturnsKnownContainer() throws ODataException {
final String name = cut.getServiceDocument().getNameBuilder().buildContainerName();
final FullQualifiedName fqn = new FullQualifiedName(PUNIT_NAME, name);
final CsdlEntityContainerInfo act = cut.getEntityContainerInfo(new FullQualifiedName(PUNIT_NAME, name));
assertNotNull(act);
assertEquals(fqn, act.getContainerName());
}
@Test
void checkEntityContainerInfoReturnsContainerIfNull() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlEntityContainerInfo act = cut.getEntityContainerInfo(null);
assertNotNull(act);
assertEquals(fqn, act.getContainerName());
}
@Test
void checkGetEntitySetReturnsNullOnUnknownSet() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlEntitySet act = cut.getEntitySet(fqn, "Hello");
assertNull(act);
}
@Test
void checkGetEntitySetReturnsNullOnUnknownNamespace() throws ODataException {
final FullQualifiedName fqn = new FullQualifiedName(PUNIT_NAME, "Hello");
final CsdlEntitySet act = cut.getEntitySet(fqn, "World");
assertNull(act);
}
@Test
void checkGetEntitySetReturnsKnownSet() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlEntitySet act = cut.getEntitySet(fqn, "Persons");
assertNotNull(act);
assertEquals("Persons", act.getName());
}
@Test
void checkGetSingletonReturnsNullOnUnknown() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
assertNull(cut.getSingleton(fqn, "Hello"));
}
@Test
void checkGetSingletonReturnsNullOnUnknownNamespace() throws ODataException {
final FullQualifiedName fqn = new FullQualifiedName(PUNIT_NAME, "Hello");
assertNull(cut.getSingleton(fqn, "CurrentUser"));
}
@Test
void checkGetSingletonReturnsKnown() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlSingleton act = cut.getSingleton(fqn, "CurrentUser");
assertNotNull(act);
assertEquals("CurrentUser", act.getName());
}
@Test
void checkGetEntityTypeReturnsNullOnUnknown() throws ODataException {
final CsdlEntityType act = cut.getEntityType(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkGetEntityTypeReturnsKnownEnum() throws ODataException {
final CsdlEntityType act = cut.getEntityType(new FullQualifiedName(PUNIT_NAME, "BusinessPartner"));
assertNotNull(act);
assertTrue(act.isAbstract());
}
@Test
void checkGetFunctionImportReturnsNullOnUnknownContainer() throws ODataException {
final CsdlFunctionImport act = cut.getFunctionImport(new FullQualifiedName("Hello", "World"), "Hello");
assertNull(act);
}
@Test
void checkGetFunctionImportReturnsNullOnUnknownFunction() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlFunctionImport act = cut.getFunctionImport(fqn, "Hello");
assertNull(act);
}
@Test
void checkGetFunctionImportReturnsKnownImport() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlFunctionImport act = cut.getFunctionImport(fqn, "Siblings");
assertNotNull(act);
}
@Test
void checkGetFunctionsReturnsNullOnUnknownFunction() throws ODataException {
final List<CsdlFunction> act = cut.getFunctions(new FullQualifiedName(PUNIT_NAME, "Hello"));
assertNull(act);
}
@Test
void checkGetFunctionsReturnsNullOnUnknownSchema() throws ODataException {
final List<CsdlFunction> act = cut.getFunctions(new FullQualifiedName("Hallo", "Welt"));
assertNull(act);
}
@Test
void checkGetFunctionsReturnsKnownFunction() throws ODataException {
final List<CsdlFunction> act = cut.getFunctions(new FullQualifiedName(PUNIT_NAME, "PopulationDensity"));
assertNotNull(act);
assertEquals(1, act.size());
assertEquals(2, act.get(0).getParameters().size());
}
@Test
void checkGetAnnotationsGroupReturnsNull() throws ODataException {
final CsdlAnnotations act = cut.getAnnotationsGroup(new FullQualifiedName(PUNIT_NAME, "Hello"), "World");
assertNull(act);
}
@Test
void checkGetTermReturnsNullOnUnknown() throws ODataException {
final CsdlTerm act = cut.getTerm(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkGetTermReturnsKnownTerm() throws ODataException {
postProcessor = new PostProcessor();
cut = new JPAEdmProvider(PUNIT_NAME, emf, postProcessor, enumPackages);
final CsdlTerm act = cut.getTerm(new FullQualifiedName("Org.OData.Measures.V1", "ISOCurrency"));
assertNotNull(act);
}
@Test
void checkTypeDefinitionReturnsNullOnUnknown() throws ODataException {
final CsdlTypeDefinition act = cut.getTypeDefinition(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkGetActionsReturnsNullOnUnknown() throws ODataException {
final List<CsdlAction> act = cut.getActions(new FullQualifiedName("Hello", "World"));
assertNull(act);
}
@Test
void checkGetActionsReturnsKnownAction() throws ODataException {
final String[] operationPackages = { "com.sap.olingo.jpa.metadata.core.edm.mapper.testaction",
"com.sap.olingo.jpa.processor.core.testmodel" };
cut = new JPAEdmProvider(PUNIT_NAME, emf, null, operationPackages);
final List<CsdlAction> act = cut.getActions(new FullQualifiedName(PUNIT_NAME, "BoundNoImport"));
assertNotNull(act);
assertEquals(1, act.size());
}
@Test
void checkGetActionImportReturnsNullOnUnknownContainer() throws ODataException {
final CsdlActionImport act = cut.getActionImport(new FullQualifiedName("Hello", "World"), "Dummy");
assertNull(act);
}
@Test
void checkGetActionImportReturnsNullOnUnknownAction() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final CsdlActionImport act = cut.getActionImport(fqn, "Dummy");
assertNull(act);
}
@Test
void checkGetActionImportReturnsKnownAction() throws ODataException {
final FullQualifiedName fqn = buildContainerFQN();
final String[] operationPackages = { "com.sap.olingo.jpa.metadata.core.edm.mapper.testaction",
"com.sap.olingo.jpa.processor.core.testmodel" };
cut = new JPAEdmProvider(PUNIT_NAME, emf, null, operationPackages);
final CsdlActionImport act = cut.getActionImport(fqn, "WithImport");
assertNotNull(act);
}
@Test
void checkConstructorThrowsExceptionOnMetadataError() throws ODataException {
final EntityManagerFactory errorEmf = JPAEntityManagerFactory.getEntityManagerFactory(ERROR_PUNIT, dataSource);
final JPAEdmProvider edmProvider = new JPAEdmProvider(ERROR_PUNIT, errorEmf, null, enumPackages);
assertThrows(ODataException.class,
() -> edmProvider.getEntityType(new FullQualifiedName(ERROR_PUNIT, "MissingCardinalityAnnotation")));
assertThrows(ODataException.class,
() -> edmProvider.getEntityType(new FullQualifiedName(ERROR_PUNIT, "MissingCardinalityAnnotation")));
}
@Test
void checkAsUserGroupRestricted() {
List<String> groups = List.of("Company");
final var act = cut.asUserGroupRestricted(groups);
assertNotEquals(cut, act);
assertEquals(groups, act.getUserGroups());
assertNotEquals(cut.getServiceDocument(), act.getServiceDocument());
}
private FullQualifiedName buildContainerFQN() {
final String name = cut.getServiceDocument().getNameBuilder().buildContainerName();
return new FullQualifiedName(PUNIT_NAME, name);
}
private static class PostProcessor implements JPAEdmMetadataPostProcessor {
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {
// Not needed
}
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
// Not needed
}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {
// Not needed
}
@Override
public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {
final String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml";
final IntermediateReferenceAccess reference = references.addReference(uri,
"annotations/Org.OData.Measures.V1.xml");
reference.addInclude("Org.OData.Core.V1", "Core");
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/util/MemberDouble.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/util/MemberDouble.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.Map;
public class MemberDouble implements Member, AnnotatedElement {
private final Member member;
private final AnnotatedElement annotatedElement;
private final Map<Class<?>, Annotation> annotations;
public MemberDouble(Member member) {
super();
this.member = member;
this.annotatedElement = (AnnotatedElement) member;
this.annotations = new HashMap<>();
}
@SuppressWarnings("unchecked")
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
if (annotations.containsKey(annotationClass))
return (T) annotations.get(annotationClass);
return annotatedElement.getAnnotation(annotationClass);
}
@Override
public Annotation[] getAnnotations() {
return annotatedElement.getAnnotations();
}
@Override
public Annotation[] getDeclaredAnnotations() {
return annotatedElement.getDeclaredAnnotations();
}
@Override
public Class<?> getDeclaringClass() {
return member.getDeclaringClass();
}
@Override
public String getName() {
return member.getName();
}
@Override
public int getModifiers() {
return member.getModifiers();
}
@Override
public boolean isSynthetic() {
return member.isSynthetic();
}
public <T extends Annotation> void addAnnotation(Class<T> clazz, T annotation) {
annotations.put(clazz, annotation);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/util/AnnotationTestHelper.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/util/AnnotationTestHelper.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.util;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Optional;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlComplexType;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlTerm;
import org.apache.olingo.commons.api.edm.provider.CsdlTypeDefinition;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.JPAReferences;
public final class AnnotationTestHelper {
private AnnotationTestHelper() {
super();
}
public static CsdlTerm addTermToCoreReferences(final JPAReferences reference, final String term, final String type,
final CsdlTypeDefinition typeDefintion) {
final var csdlTerm = mock(CsdlTerm.class);
when(reference.getTerm(new FullQualifiedName("Org.OData.Core.V1", term)))
.thenReturn(Optional.of(csdlTerm));
when(reference.getType(new FullQualifiedName("Core", type)))
.thenReturn(Optional.of(typeDefintion));
when(csdlTerm.getName()).thenReturn(term);
when(csdlTerm.getType()).thenReturn("Core." + type);
return csdlTerm;
}
public static CsdlTerm addTermToCoreReferences(final JPAReferences reference, final String term,
final String type, final List<CsdlProperty> properties) {
final var termFilter = mock(CsdlTerm.class);
final var complexType = new CsdlComplexType();
complexType.setProperties(properties);
when(reference.getTerm(new FullQualifiedName("Org.OData.Core.V1", term)))
.thenReturn(Optional.of(termFilter));
when(reference.getType(new FullQualifiedName("Core", type)))
.thenReturn(Optional.of(complexType));
when(termFilter.getName()).thenReturn(term);
when(termFilter.getType()).thenReturn("Core." + type);
return termFilter;
}
public static CsdlTerm addTermToCapabilitiesReferences(final JPAReferences reference, final String term,
final String type, final List<CsdlProperty> properties) {
final var termFilter = mock(CsdlTerm.class);
final var complexType = new CsdlComplexType();
complexType.setProperties(properties);
when(reference.getTerm(new FullQualifiedName("Org.OData.Capabilities.V1", term)))
.thenReturn(Optional.of(termFilter));
when(reference.getType(new FullQualifiedName("Capabilities", type)))
.thenReturn(Optional.of(complexType));
when(termFilter.getName()).thenReturn(term);
when(termFilter.getType()).thenReturn("Capabilities." + type);
return termFilter;
}
public static CsdlAnnotation createCoreAnnotation(final String term) {
final var annotation = mock(CsdlAnnotation.class);
when(annotation.getTerm()).thenReturn("Org.OData.Core.V1." + term);
return annotation;
}
public static CsdlAnnotation createCapabilitiesAnnotation(final String term) {
final var annotation = mock(CsdlAnnotation.class);
when(annotation.getTerm()).thenReturn("Org.OData.Capabilities.V1." + term);
return annotation;
}
public static CsdlProperty createTermProperty(final String name, final String type) {
final var property = mock(CsdlProperty.class);
when(property.getType()).thenReturn(type);
when(property.isCollection()).thenReturn(false);
when(property.getName()).thenReturn(name);
return property;
}
public static CsdlProperty createTermCollectionProperty(final String name, final String type) {
final var property = mock(CsdlProperty.class);
when(property.getType()).thenReturn(type);
when(property.isCollection()).thenReturn(true);
when(property.getName()).thenReturn(name);
return property;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/MapCacheFunctionTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/MapCacheFunctionTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelInternalException;
class MapCacheFunctionTest {
@Test
void checkCacheReturnsGivenValue() throws ODataJPAModelException {
final var act = new MapCacheFunction<>(this::functionReturnString, "Test", "String");
assertFalse(act.get().isEmpty());
assertEquals(1, act.get().size());
assertEquals("String", act.get().get("Test"));
}
@Test
void checkCacheThrowsExceptionOnNull() {
final var act = new MapCacheFunction<>(this::functionReturnNull, "Test", "String");
assertThrows(NullPointerException.class, act::get);
}
@Test
void checkCacheThrowsException() {
final var act = new MapCacheFunction<>(this::functionThrows, "Test", "String");
assertThrows(ODataJPAModelException.class, act::get);
}
Map<String, String> functionReturnString(final String first, final String last) {
return Map.of("Test", "String");
}
Map<String, String> functionReturnNull(final String first, final String last) { // NOSONAR
return null;
}
Map<String, String> functionThrows(final String first, final String last) {
throw new ODataJPAModelInternalException(new ODataJPAModelException(MessageKeys.DB_TYPE_NOT_DETERMINED, first,
last));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/InstanceCacheSupplierTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/InstanceCacheSupplierTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelInternalException;
class InstanceCacheSupplierTest {
@Test
void checkCacheReturnsGivenValue() throws ODataJPAModelException {
var act = new InstanceCacheSupplier<>(this::supplierReturnString);
assertTrue(act.get().isPresent());
assertEquals("TestString", act.get().get());
}
@Test
void checkCacheReturnsEmpty() throws ODataJPAModelException {
var act = new InstanceCacheSupplier<>(this::supplierReturnNull);
assertTrue(act.get().isEmpty());
}
@Test
void checkCacheThrowsException() {
var act = new InstanceCacheSupplier<>(this::supplierThrows);
assertThrows(ODataJPAModelException.class, act::get);
}
String supplierReturnString() {
return "TestString";
}
String supplierReturnNull() {
return null;
}
String supplierThrows() {
throw new ODataJPAModelInternalException(new ODataJPAModelException(MessageKeys.DB_TYPE_NOT_DETERMINED));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/InstanceCacheFunctionTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/InstanceCacheFunctionTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelInternalException;
class InstanceCacheFunctionTest {
@Test
void checkCacheReturnsGivenValue() throws ODataJPAModelException {
var act = new InstanceCacheFunction<>(this::functionReturnString, "Test", "String");
assertTrue(act.get().isPresent());
assertEquals("TestString", act.get().get());
}
@Test
void checkCacheReturnsEmpty() throws ODataJPAModelException {
var act = new InstanceCacheFunction<>(this::functionReturnNull, "Test", "String");
assertTrue(act.get().isEmpty());
}
@Test
void checkCacheThrowsException() {
var act = new InstanceCacheFunction<>(this::functionThrows, "Test", "String");
assertThrows(ODataJPAModelException.class, act::get);
}
String functionReturnString(String first, String last) {
return first + last;
}
String functionReturnNull(String first, String last) { // NOSONAR
return null;
}
String functionThrows(String first, String last) {
throw new ODataJPAModelInternalException(new ODataJPAModelException(MessageKeys.DB_TYPE_NOT_DETERMINED, first,
last));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/ListCacheSupplierTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/ListCacheSupplierTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelInternalException;
class ListCacheSupplierTest {
@Test
void checkCacheReturnsGivenValue() throws ODataJPAModelException {
var act = new ListCacheSupplier<>(this::supplierReturnString);
assertFalse(act.get().isEmpty());
assertEquals(2, act.get().size());
assertEquals("Test", act.get().get(0));
assertEquals("String", act.get().get(1));
}
@Test
void checkCacheThrowsExceptionOnNull() {
var act = new ListCacheSupplier<>(this::supplierReturnNull);
assertThrows(NullPointerException.class, act::get);
}
@Test
void checkCacheThrowsException() {
var act = new ListCacheSupplier<>(this::supplierThrows);
assertThrows(ODataJPAModelException.class, act::get);
}
List<String> supplierReturnString() {
return List.of("Test", "String");
}
List<String> supplierReturnNull() {
return null;
}
List<String> supplierThrows() {
throw new ODataJPAModelInternalException(new ODataJPAModelException(MessageKeys.DB_TYPE_NOT_DETERMINED));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/MapCacheSupplierTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/cache/MapCacheSupplierTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelInternalException;
class MapCacheSupplierTest {
@Test
void checkCacheReturnsGivenValue() throws ODataJPAModelException {
var act = new MapCacheSupplier<>(this::supplierReturnString);
assertFalse(act.get().isEmpty());
assertEquals(1, act.get().size());
assertEquals("String", act.get().get("Test"));
}
@Test
void checkCacheThrowsExceptionOnNull() {
var act = new MapCacheSupplier<>(this::supplierReturnNull);
assertThrows(NullPointerException.class, act::get);
}
@Test
void checkCacheThrowsException() {
var act = new MapCacheSupplier<>(this::supplierThrows);
assertThrows(ODataJPAModelException.class, act::get);
}
Map<String, String> supplierReturnString() {
return Map.of("Test", "String");
}
Map<String, String> supplierReturnNull() {
return null;
}
Map<String, String> supplierThrows() {
throw new ODataJPAModelInternalException(new ODataJPAModelException(MessageKeys.DB_TYPE_NOT_DETERMINED));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.exception;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.testmodel.LocaleEnumeration;
class TestODataJPAMessageTextBuffer {
private static final String BUNDLE_NAME = "test-i18n";
private ODataJPAMessageTextBuffer cut;
@BeforeEach
void setup() {
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME);
}
@Test
void checkDefaultLocale() {
assertEquals(ODataJPAMessageTextBuffer.DEFAULT_LOCALE.getLanguage(), cut.getLocale().getLanguage());
}
@Test
void checkSetLocaleGerman() {
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, Locale.GERMANY);
assertEquals("de", cut.getLocale().getLanguage());
}
@Test
void checkSetLocaleReset() {
// Set first to German
checkSetLocaleGerman();
// Then reset to default
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME);
assertEquals(ODataJPAMessageTextBuffer.DEFAULT_LOCALE.getLanguage(), cut.getLocale().getLanguage());
}
@Test
void checkGetDefaultLocaleText() {
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("An English message", act);
}
@Test
void checkGetGermanText() {
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, Locale.GERMANY);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("Ein deutscher Text", act);
}
// %1$s
@Test
void checkGetTextWithParameter() {
final String act = cut.getText(this, "SECOND_MESSAGE", "Hugo", "Willi");
assertEquals("Hugo looks for Willi", act);
}
@Test
void checkSetLocalesNull() {
final Enumeration<Locale> locales = null;
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("An English message", act);
}
@Test
void checkSetLocalesRestDefaultWithNull() {
// First set to German
checkSetLocaleGerman();
// Then reset default
final Enumeration<Locale> locales = null;
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("An English message", act);
}
@Test
void checkSetLocalesRestDefaultWithEmpty() {
// First set to German
checkSetLocaleGerman();
// Then reset default
final Enumeration<Locale> locales = new LocaleEnumeration(new ArrayList<>());
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("An English message", act);
}
@Test
void checkSetLocalesFirstMatches() {
final ArrayList<Locale> localesList = new ArrayList<>();
localesList.add(Locale.GERMAN);
localesList.add(Locale.CANADA_FRENCH);
final Enumeration<Locale> locales = new LocaleEnumeration(localesList);
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("Ein deutscher Text", act);
}
@Test
void checkSetLocalesSecondMatches() {
final ArrayList<Locale> localesList = new ArrayList<>();
localesList.add(Locale.CANADA_FRENCH);
localesList.add(Locale.GERMAN);
final Enumeration<Locale> locales = new LocaleEnumeration(localesList);
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("Ein deutscher Text", act);
}
@Test
void checkSetLocalesNonMatches() {
final ArrayList<Locale> localesList = new ArrayList<>();
localesList.add(Locale.CANADA_FRENCH);
localesList.add(Locale.SIMPLIFIED_CHINESE);
final Enumeration<Locale> locales = new LocaleEnumeration(localesList);
cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales);
final String act = cut.getText(this, "FIRST_MESSAGE");
assertEquals("An English message", act);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.exception;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Locale;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.processor.core.testmodel.LocaleEnumeration;
class TestODataJPAModelException {
private static final String BUNDLE_NAME = "test-i18n";
@Test
void checkTextInDefaultLocale() {
try {
RaiseException();
} catch (final ODataJPAException e) {
assertEquals("An English message", e.getMessage());
return;
}
fail();
}
@Test
void checkTextInGerman() {
try {
final ArrayList<Locale> localesList = new ArrayList<>();
localesList.add(Locale.GERMAN);
final Enumeration<Locale> locales = new LocaleEnumeration(localesList);
TestException.setLocales(locales);
RaiseException();
} catch (final ODataJPAException e) {
assertEquals("Ein deutscher Text", e.getMessage());
return;
}
fail();
}
@Test
void checkTextInDefaultLocaleWithParameter() {
try {
RaiseExceptionParam();
} catch (final ODataJPAException e) {
assertEquals("Willi looks for Hugo", e.getMessage());
return;
}
fail();
}
@Test
void checkTextOnlyCause() {
try {
RaiseExceptionCause();
} catch (final ODataJPAException e) {
assertEquals("Test text from cause", e.getMessage());
return;
}
fail();
}
@Test
void checkTextIdAndCause() {
try {
RaiseExceptionIDCause();
} catch (final ODataJPAException e) {
assertEquals("An English message", e.getMessage());
return;
}
fail();
}
@Test
void checkTextIdAndCauseAndParameter() {
try {
RaiseExceptionIDCause("Willi", "Hugo");
} catch (final ODataJPAException e) {
assertEquals("Willi looks for Hugo", e.getMessage());
return;
}
fail();
}
@Test
void checkTextNullId() {
try {
RaiseEmptyIDException();
} catch (final ODataJPAException e) {
assertEquals("No message text found", e.getMessage());
return;
}
fail();
}
private void RaiseExceptionIDCause(final String... params) throws TestException {
try {
raiseNullPointer();
} catch (final NullPointerException e) {
if (params.length == 0)
throw new TestException("FIRST_MESSAGE", e);
else
throw new TestException("SECOND_MESSAGE", e, params);
}
}
private void RaiseExceptionCause() throws ODataJPAException {
try {
raiseNullPointer();
} catch (final NullPointerException e) {
throw new TestException(e);
}
}
private void raiseNullPointer() throws NullPointerException {
throw new NullPointerException("Test text from cause");
}
private void RaiseExceptionParam() throws ODataJPAException {
throw new TestException("SECOND_MESSAGE", "Willi", "Hugo");
}
private void RaiseException() throws ODataJPAException {
throw new TestException("FIRST_MESSAGE");
}
private void RaiseEmptyIDException() throws ODataJPAException {
throw new TestException("");
}
private static class TestException extends ODataJPAException {
private static final long serialVersionUID = 1L;
public TestException(final String id) {
super(id);
}
public TestException(final String id, final String... params) {
super(id, params);
}
public TestException(final Throwable e) {
super(e);
}
public TestException(final String id, final Throwable e) {
super(id, e);
}
public TestException(final String id, final Throwable e, final String[] params) {
super(id, e, 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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateServiceDocumentTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateServiceDocumentTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.edm.EdmAction;
import org.apache.olingo.commons.api.edm.EdmBindingTarget;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer;
import org.apache.olingo.commons.api.edm.provider.CsdlSchema;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
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.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey;
class IntermediateServiceDocumentTest extends TestMappingRoot {
private JPAServiceDocument cut;
private List<AnnotationProvider> annotationProvider;
static Stream<Arguments> getEntityTypeByFqn() {
return Stream.of(
arguments(new FullQualifiedName("com.sap.olingo.jpa.BusinessPartner"), false),
arguments(new FullQualifiedName("com.sap.olingo.jpa.Dummy"), true),
arguments(new FullQualifiedName("dummy.BusinessPartner"), true));
}
static Stream<Arguments> getEntityTypeByEsName() {
return Stream.of(
arguments("BusinessPartners", false),
arguments("Dummy", true));
}
static Stream<Arguments> getEntitySetByExternalName() {
return Stream.of(
arguments("BusinessPartners", false),
arguments("Dummy", true));
}
static Stream<Arguments> getTopLevelEntityByExternalName() {
return Stream.of(
arguments("BusinessPartners", false),
arguments("CurrentUser", false),
arguments("Dummy", true));
}
static Stream<Arguments> getEnumType() {
return Stream.of(
arguments("com.sap.olingo.jpa.AccessRights", false),
arguments("com.sap.olingo.jpa.Dummy", true),
arguments("Unknown.AccessRights", true));
}
static Stream<Arguments> getEntityTypeBySingletonName() {
return Stream.of(
arguments("CurrentUser", false),
arguments("Dummy", true));
}
@BeforeEach
void setup() throws ODataJPAModelException {
annotationProvider = new ArrayList<>();
cut = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null,
new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }, annotationProvider);
}
@Test
void checkServiceDocumentCanBeCreated() throws ODataJPAModelException {
assertNotNull(new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null,
new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }, annotationProvider));
}
@Test
void checkServiceDocumentGetSchemaList() throws ODataJPAModelException {
assertEquals(1, cut.getEdmSchemas().size(), "Wrong number of schemas");
}
@Test
void checkServiceDocumentGetContainer() throws ODataJPAModelException {
assertNotNull(cut.getEdmEntityContainer(), "Entity Container not found");
}
@Test
void checkServiceDocumentGetContainerFromSchema() throws ODataJPAModelException {
final List<CsdlSchema> schemas = cut.getEdmSchemas();
final CsdlSchema schema = schemas.get(0);
assertNotNull(schema.getEntityContainer(), "Entity Container not found");
}
@Test
void checkServiceDocumentGetEntitySetsFromContainer() throws ODataJPAModelException {
final CsdlEntityContainer container = cut.getEdmEntityContainer();
assertNotNull(container.getEntitySets(), "Entity Container not found");
}
@Test
void checkHasEtagReturnsTrueOnVersion() {
final EdmBindingTarget target = mock(EdmBindingTarget.class);
final EdmEntityType et = mock(EdmEntityType.class);
when(target.getEntityType()).thenReturn(et);
when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName(PUNIT_NAME, "BusinessPartner"));
assertTrue(cut.hasETag(target));
}
@Test
void checkHasEtagReturnsFalseWithoutVersion() throws ODataJPAModelException {
final EdmBindingTarget target = mock(EdmBindingTarget.class);
final EdmEntityType et = mock(EdmEntityType.class);
when(target.getEntityType()).thenReturn(et);
when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName(PUNIT_NAME, "Country"));
final JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, null,
annotationProvider);
assertFalse(svc.hasETag(target));
}
@ParameterizedTest
@MethodSource("getEnumType")
void checkGetEnumType(final String enumName, final boolean isNull) {
if (isNull)
assertNull(cut.getEnumType(enumName));
else
assertNotNull(cut.getEnumType(enumName));
}
@ParameterizedTest
@MethodSource("getEntityTypeByEsName")
void checkGetEntityTypeByEsName(final String esName, final boolean isNull) throws ODataJPAModelException {
if (isNull)
assertNull(cut.getEntity(esName));
else
assertNotNull(cut.getEntity(esName));
}
@ParameterizedTest
@MethodSource("getEntityTypeBySingletonName")
void checkGetEntityTypeBySingletonName(final String singletonName, final boolean isNull)
throws ODataJPAModelException {
if (isNull)
assertNull(cut.getEntity(singletonName));
else
assertNotNull(cut.getEntity(singletonName));
}
@ParameterizedTest
@MethodSource("getEntityTypeByFqn")
void checkGetEntityTypeByFqn(final FullQualifiedName etFqn, final boolean isNull) {
if (isNull)
assertNull(cut.getEntity(etFqn));
else
assertNotNull(cut.getEntity(etFqn));
}
@Test
void checkGetEntityTypeByEdmType() throws ODataJPAModelException {
final EdmEntityType type = mock(EdmEntityType.class);
when(type.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(type.getName()).thenReturn("BusinessPartner");
assertNotNull(cut.getEntity(type));
}
@Test
void checkGetEntityTypeByEdmTypeReturnNullOnUnknown() throws ODataJPAModelException {
final EdmEntityType type = mock(EdmEntityType.class);
when(type.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(type.getName()).thenReturn("Unknown");
assertNull(cut.getEntity(type));
}
@Test
void checkGetEntityTypeByEdmTypeReturnNullOnUnknownSchema() throws ODataJPAModelException {
final EdmEntityType type = mock(EdmEntityType.class);
when(type.getNamespace()).thenReturn("Unknown");
when(type.getName()).thenReturn("BoundNoImport");
assertNull(cut.getEntity(type));
}
@Test
void checkGetComplexTypeByEdmType() {
final EdmComplexType type = mock(EdmComplexType.class);
when(type.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(type.getName()).thenReturn("CommunicationData");
assertNotNull(cut.getComplexType(type));
}
@Test
void checkGetComplexTypeByEdmTypeReturnNullOnUnknown() {
final EdmComplexType type = mock(EdmComplexType.class);
when(type.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(type.getName()).thenReturn("Unknown");
assertNull(cut.getComplexType(type));
}
@Test
void checkGetComplexTypeByEdmTypeReturnNullOnUnknownSchema() {
final EdmComplexType type = mock(EdmComplexType.class);
when(type.getNamespace()).thenReturn("Unknown");
when(type.getName()).thenReturn("BoundNoImport");
assertNull(cut.getComplexType(type));
}
@Test
void checkGetComplexTypeByClass() {
assertNotNull(cut.getComplexType(AdministrativeDivisionDescriptionKey.class));
}
@Test
void checkGetComplexTypeByClassReturnNullOnUnknown() {
assertNull(cut.getComplexType(AdministrativeDivisionKey.class));
}
@Test
void checkGetBoundAction() throws ODataJPAModelException {
final EdmAction action = mock(EdmAction.class);
when(action.getNamespace()).thenReturn(PUNIT_NAME);
when(action.getName()).thenReturn("BoundNoImport");
when(action.getBindingParameterTypeFqn()).thenReturn(new FullQualifiedName(PUNIT_NAME, "Person"));
when(action.isBound()).thenReturn(true);
final JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null,
new String[] { "com.sap.olingo.jpa.metadata.core.edm.mapper.testaction" }, annotationProvider);
assertNotNull(svc.getAction(action));
}
@Test
void checkGetUnBoundAction() throws ODataJPAModelException {
final EdmAction action = mock(EdmAction.class);
when(action.getNamespace()).thenReturn(PUNIT_NAME);
when(action.getName()).thenReturn("WithImport");
when(action.getBindingParameterTypeFqn()).thenReturn(null);
when(action.isBound()).thenReturn(false);
final JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null,
new String[] { "com.sap.olingo.jpa.metadata.core.edm.mapper.testaction" }, annotationProvider);
assertNotNull(svc.getAction(action));
}
@Test
void checkGetActionReturnNullOnUnknownAction() {
final EdmAction action = mock(EdmAction.class);
when(action.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(action.getName()).thenReturn("Unknown");
assertNull(cut.getAction(action));
}
@Test
void checkGetActionReturnNullOnUnknownSchema() {
final EdmAction action = mock(EdmAction.class);
when(action.getNamespace()).thenReturn("Unknown");
when(action.getName()).thenReturn("BoundNoImport");
assertNull(cut.getAction(action));
}
@Test
void checkGetFunction() {
final EdmFunction function = mock(EdmFunction.class);
when(function.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(function.getName()).thenReturn("ConvertToQkm");
assertNotNull(cut.getFunction(function));
}
@Test
void checkGetFunctionReturnNullOnUnknownFunction() {
final EdmFunction function = mock(EdmFunction.class);
when(function.getNamespace()).thenReturn("com.sap.olingo.jpa");
when(function.getName()).thenReturn("Unknown");
assertNull(cut.getFunction(function));
}
@Test
void checkGetFunctionReturnNullOnUnknownSchema() {
final EdmFunction function = mock(EdmFunction.class);
when(function.getNamespace()).thenReturn("Unknown");
when(function.getName()).thenReturn("BoundNoImport");
assertNull(cut.getFunction(function));
}
@Test
void checkHasMediaETagNotSupported() {
final EdmBindingTarget target = mock(EdmBindingTarget.class);
assertFalse(cut.hasMediaETag(target));
}
@Test
void checkGetEntityTypeReturnsSetCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
assertNotNull(cut.getEntity("Business_Partner".toUpperCase()));
}
@Test
void checkGetEntityTypeReturnsEdmTypCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
final EdmType edmType = mock(EdmType.class);
when(edmType.getName()).thenReturn("Business_Partner");
when(edmType.getNamespace()).thenReturn("test");
assertNotNull(cut.getEntity(edmType));
}
@Test
void checkGetPropertyReturnsCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
assertEquals("creationDateTime", cut.getEntity("Business_Partner".toUpperCase()).getAttribute("creationDateTime")
.get().getExternalName());
}
@Test
void checkGetComplexTypeReturnsCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
final EdmComplexType type = mock(EdmComplexType.class);
when(type.getNamespace()).thenReturn("test");
when(type.getName()).thenReturn("T_CommunicationData");
assertNotNull(cut.getComplexType(type));
}
@Test
void checkGetContainerReturnsCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
assertEquals("service_container", cut.getEdmEntityContainer().getName());
}
@Test
void checkGetEnumReturnsCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
assertNotNull(cut.getEnumType("test.E_AccessRights"));
}
@Test
void checkGetActionCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
final EdmAction action = mock(EdmAction.class);
when(action.getNamespace()).thenReturn("test");
when(action.getName()).thenReturn("O_BoundNoImport");
when(action.getBindingParameterTypeFqn()).thenReturn(new FullQualifiedName("test", "Person"));
when(action.isBound()).thenReturn(true);
assertNotNull(cut.getAction(action));
}
@Test
void checkGetFunctionCustomName() throws ODataJPAModelException {
cut = createCutWithCustomNameBuilder();
final EdmFunction function = mock(EdmFunction.class);
when(function.getNamespace()).thenReturn("test");
when(function.getName()).thenReturn("O_sum");
assertNotNull(cut.getFunction(function));
}
@Test
void checkGetClaimsReturnsAllClaims() throws ODataJPAModelException {
final Map<String, JPAProtectionInfo> act = cut.getClaims();
assertNotNull(act);
assertTrue(act.containsKey("BuildingNumber"));
}
@Test
void checkGetEntityTypeOfSingleton() {
final FullQualifiedName fqn = new FullQualifiedName(PUNIT_NAME, "CurrentUser");
final JPAEntityType act = cut.getEntity(fqn);
assertNotNull(act);
}
@ParameterizedTest
@MethodSource("getEntitySetByExternalName")
void checkGetEntitySetByExternalName(final String esName, final boolean isEmpty) throws ODataJPAModelException {
if (isEmpty)
assertFalse(cut.getEntitySet(esName).isPresent());
else
assertTrue(cut.getEntitySet(esName).isPresent());
}
@ParameterizedTest
@MethodSource("getTopLevelEntityByExternalName")
void checkGetTopLevelEntityByExternalName(final String esName, final boolean isEmpty) throws ODataJPAModelException {
if (isEmpty)
assertFalse(cut.getTopLevelEntity(esName).isPresent());
else
assertTrue(cut.getTopLevelEntity(esName).isPresent());
}
private IntermediateServiceDocument createCutWithCustomNameBuilder() throws ODataJPAModelException {
return new IntermediateServiceDocument(new CustomJPANameBuilder(), emf.getMetamodel(), null,
new String[] { "com.sap.olingo.jpa.processor.core.testmodel",
"com.sap.olingo.jpa.metadata.core.edm.mapper.testaction" }, annotationProvider);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateJavaFunctionTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateJavaFunctionTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.ODataFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleFunctionForFilter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaEmConstructor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaFunctions;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaPrivateConstructor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoFunctions;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoParameterConstructor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongFunctionConstructor;
class IntermediateJavaFunctionTest extends TestMappingRoot {
private TestHelper helper;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
}
@Test
void checkInternalNameEqualMethodName() throws ODataJPAModelException {
final IntermediateFunction act = createFunction(ExampleJavaOneFunction.class, "sum");
assertEquals("sum", act.getInternalName());
}
@Test
void checkExternalNameEqualMethodName() throws ODataJPAModelException {
final IntermediateFunction act = createFunction(ExampleJavaOneFunction.class, "sum");
assertEquals("Sum", act.getExternalName());
}
@Test
void checkEmptyParameterNameThrowsException() throws ODataJPAModelException {
final IntermediateFunction act = createFunction(ExampleJavaFunctions.class, "nameEmpty");
assertThrows(ODataJPAModelException.class, () -> act.getParameter("rights"));
}
@Test
void checkReturnsConvertedPrimitiveReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum");
assertNotNull(act.getEdmItem());
assertNotNull(act.getEdmItem().getReturnType());
assertEquals("Edm.Int32", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsConvertedPrimitiveParameterTypes() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum");
assertNotNull(act.getEdmItem());
assertNotNull(act.getEdmItem().getParameters());
assertEquals(2, act.getEdmItem().getParameters().size());
assertNotNull(act.getEdmItem().getParameter("A"));
assertNotNull(act.getEdmItem().getParameter("B"));
assertEquals("Edm.Int16", act.getEdmItem().getParameter("A").getType());
assertEquals("Edm.Int32", act.getEdmItem().getParameter("B").getType());
}
@ParameterizedTest
@CsvSource({
"errorNonPrimitiveParameter, ForNonPrimitiveParameter",
"errorReturnType, AnnotatedReturnTypeNEDeclaredType",
"returnCollectionWithoutReturnType, CollectionAndReturnTypeEmpty",
"wrongReturnType, NotSupportedReturnType"
})
void checkThrowsExceptionForParameterError(final String functionName, final String message)
throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, functionName);
assertThrows(ODataJPAModelException.class, act::getEdmItem, message);
}
@Test
void checkReturnsFalseForIsBound() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum");
assertNotNull(act.getEdmItem());
assertEquals(false, act.getEdmItem().isBound());
}
@Test
void checkReturnsTrueForHasFunctionImport() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum");
assertTrue(act.hasImport());
}
@Test
void checkReturnsAnnotatedName() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum");
assertEquals("Add", act.getExternalName());
}
@Test
void checkIgnoresGivenIsBound() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum");
assertFalse(act.getEdmItem().isBound());
assertFalse(act.isBound());
}
@Test
void checkIgnoresGivenHasFunctionImport() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum");
assertTrue(act.hasImport());
}
@Test
void checkGetParameterReturnsNullIfUnknownName() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType");
assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
assertNull(act.getParameter("test"));
}
@Test
void checkGetParameterReturnsNullIfUnknownType() throws ODataJPAModelException, NoSuchMethodException,
SecurityException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType");
final Parameter parameter = ExampleJavaFunctions.class.getMethod("sum", short.class, int.class)
.getParameters()[1];
assertNull(act.getParameter(parameter));
}
@Test
void checkReturnsEnumerationTypeAsParameter() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType");
assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
JPAParameter param = act.getParameter("arg0");
if (param == null)
param = act.getParameter("rights");
assertNotNull(param);
assertEquals("com.sap.olingo.jpa.AccessRights", param.getTypeFQN().getFullQualifiedNameAsString());
}
@Test
void checkIgnoresParameterAsPartFromEdmFunction() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "div");
assertNotNull(act.getEdmItem());
assertEquals(2, act.getEdmItem().getParameters().size());
assertNotNull(act.getEdmItem().getParameter("A"));
assertNotNull(act.getEdmItem().getParameter("B"));
}
@Test
void checkReturnsFacetForNumbersOfReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "now");
assertFalse(act.getEdmItem().getReturnType().isNullable());
assertEquals(9, act.getEdmItem().getReturnType().getPrecision());
assertEquals(3, act.getEdmItem().getReturnType().getScale());
}
@Test
void checkReturnsFacetForStringsAndGeoOfReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "determineLocation");
assertEquals(60, act.getEdmItem().getReturnType().getMaxLength());
assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getReturnType().getSrid().getDimension());
assertEquals("4326", act.getEdmItem().getReturnType().getSrid().toString());
}
@Test
void checkReturnsParameterFacetWithMapping() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum");
assertNotNull(act.getEdmItem().getParameters());
assertNotNull(act.getEdmItem().getParameters().get(0).getMapping());
assertEquals(Short.class, act.getEdmItem().getParameters().get(0).getMapping().getMappedJavaClass());
}
@Test
void checkReturnsIsCollectionIfDefinedReturnTypeIsSubclassOfCollection() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnCollection");
assertTrue(act.getEdmItem().getReturnType().isCollection());
assertEquals("Edm.String", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsEmbeddableTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEmbeddable");
assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsEmbeddableCollectionTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEmbeddableCollection");
assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType());
assertTrue(act.getEdmItem().getReturnType().isCollection());
}
@Test
void checkReturnsEntityTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEntity");
assertEquals("com.sap.olingo.jpa.Person", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsEnumerationTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType");
assertEquals("com.sap.olingo.jpa.ABCClassification", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsEnumerationCollectionTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationCollection");
assertEquals("com.sap.olingo.jpa.ABCClassification", act.getEdmItem().getReturnType().getType());
assertTrue(act.getEdmItem().getReturnType().isCollection());
}
@Test
void checkThrowsExceptionOnVoidAsReturnType() throws ODataJPAModelException {
// The function MUST specify a return type using the edm:ReturnType element. The return type must be a primitive,
// entity or complex type, or a collection of primitive, entity or complex types.
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnsNothing");
final ODataJPAModelException e = assertThrows(ODataJPAModelException.class, () -> act.getEdmItem().getReturnType()
.getType());
assertEquals(MessageKeys.FUNC_RETURN_TYPE_EXP.toString(), e.getId());
}
@Test
void checkExceptConstructorWithoutParameter() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaTwoFunctions.class, "multi");
assertNotNull(act.getEdmItem());
}
@Test
void checkExceptConstructorWithHeaderAndParameter() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum");
assertNotNull(act.getEdmItem());
}
@Test
void checkExceptConstructorWithEntityManagerParameter() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaEmConstructor.class, "sum");
assertNotNull(act.getEdmItem());
}
@Test
void checkExceptConstructorForFilterFunction() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleFunctionForFilter.class, "at");
assertNotNull(act.getEdmItem());
}
@Test
void checkThrowsExceptionOnPrivateConstructor() {
assertThrows(ODataJPAModelException.class, () -> {
createFunction(ExampleJavaPrivateConstructor.class, "sum");
});
}
@Test
void checkThrowsExceptionOnNoConstructorAsSpecified() {
assertThrows(ODataJPAModelException.class, () -> {
createFunction(ExampleJavaTwoParameterConstructor.class, "sum");
});
}
@Test
void checkThrowsExceptionOnNoConstructorWithEmAndQuery() {
assertThrows(ODataJPAModelException.class, () -> {
createFunction(WrongFunctionConstructor.class, "sum");
});
}
@Test
void checkGetReturnType() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaEmConstructor.class, "sum");
act.getEdmItem();
assertNotNull(act.getReturnType());
}
@Test
void checkGetGroupsReturnsGiven() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum");
assertArrayEquals(new String[] { "Person", "Company" }, act.getUserGroups().toArray(new String[] {}));
}
@Test
void checkGetGroupsReturnsEmptyListIfNoProvided() throws ODataJPAModelException {
final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "determineLocation");
assertTrue(act.getUserGroups().isEmpty());
}
private IntermediateJavaFunction createFunction(final Class<? extends ODataFunction> clazz, final String method)
throws ODataJPAModelException {
for (final Method m : clazz.getMethods()) {
final EdmFunction functionDescription = m.getAnnotation(EdmFunction.class);
if (functionDescription != null && method.equals(m.getName())) {
return new IntermediateJavaFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME), functionDescription, m,
helper.schema);
}
}
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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateStructuredTypeVirtualAttributeTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateStructuredTypeVirtualAttributeTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static jakarta.persistence.metamodel.Attribute.PersistentAttributeType.BASIC;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import jakarta.persistence.metamodel.ManagedType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class IntermediateStructuredTypeVirtualAttributeTest {
private final static String COLUMN_NAME = "\"Test\"";
private IntermediateStructuredType.VirtualAttribute<?, ?> cut;
private ManagedType<?> managedType;
@BeforeEach
void setup() {
managedType = mock(ManagedType.class);
cut = new IntermediateStructuredType.VirtualAttribute<>(managedType, COLUMN_NAME);
}
@Test
void checkGetJavaTypeReturnsNull() {
assertNull(cut.getJavaType());
}
@Test
void checkIsAssociationReturnsFalse() {
assertFalse(cut.isAssociation());
}
@Test
void checkIsCollectionReturnsFalse() {
assertFalse(cut.isCollection());
}
@Test
void checkPersistentAttributeTypeIsBasic() {
assertEquals(BASIC, cut.getPersistentAttributeType());
}
@Test
void checkGetNamerReturnsLowerCase() {
assertEquals("test", cut.getName());
}
@Test
void checkGetJavaMemberReturnsNull() {
assertNull(cut.getJavaMember());
}
@Test
void checkGetDeclaringTypeReturnsParent() {
assertEquals(managedType, cut.getDeclaringType());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateContainerTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateContainerTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import jakarta.persistence.metamodel.EntityType;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet;
import org.apache.olingo.commons.api.edm.provider.CsdlFunctionImport;
import org.apache.olingo.commons.api.edm.provider.CsdlNavigationPropertyBinding;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
import org.reflections8.scanners.SubTypesScanner;
import org.reflections8.scanners.TypeAnnotationsScanner;
import org.reflections8.util.ConfigurationBuilder;
import org.reflections8.util.FilterBuilder;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityContainerAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.processor.core.testmodel.BestOrganization;
import com.sap.olingo.jpa.processor.core.util.TestDataConstants;
class IntermediateContainerTest extends TestMappingRoot {
private static final String PACKAGE1 = "com.sap.olingo.jpa.metadata.core.edm.mapper.impl";
private static final String PACKAGE2 = "com.sap.olingo.jpa.processor.core.testmodel";
private final HashMap<String, IntermediateSchema> schemas = new HashMap<>();
private Set<EntityType<?>> etList;
private IntermediateSchema schema;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateReferences references;
@BeforeEach
void setup() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
references = mock(IntermediateReferences.class);
final Reflections reflections =
new Reflections(
new ConfigurationBuilder()
.forPackages(PACKAGE1, PACKAGE2)
.filterInputsBy(new FilterBuilder().includePackage(PACKAGE1, PACKAGE2))
.setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner()));
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>(), references);
schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), reflections,
annotationInfo);
etList = emf.getMetamodel().getEntities();
schemas.put(PUNIT_NAME, schema);
}
@Test
void checkContainerCanBeCreated() {
assertNotNull(new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(PUNIT_NAME), schemas, annotationInfo));
}
@Test
void checkGetName() {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
assertEquals("ComSapOlingoJpaContainer", container.getExternalName());
}
@Test
void checkGetNoEntitySets() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
assertEquals(TestDataConstants.NO_ENTITY_SETS.value, container.getEdmItem().getEntitySets().size());
}
@Test
void checkGetNoSingletons() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
assertEquals(TestDataConstants.NO_SINGLETONS.value, container.getEdmItem().getSingletons().size());
}
@Test
void checkGetEntitySetName() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) return;
}
fail();
}
@Test
void checkGetEntitySetType() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) {
assertEquals(container.buildFQN("BusinessPartner"), entitySet.getTypeFQN());
return;
}
}
fail();
}
@Test
void checkGetNoNavigationPropertyBindings() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) {
assertEquals(4, entitySet.getNavigationPropertyBindings().size());
return;
}
}
fail();
}
@Test
void checkGetNavigationPropertyBindingsTarget() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) {
for (final CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) {
if ("Roles".equals(binding.getPath())) {
assertEquals("BusinessPartnerRoles", binding.getTarget());
return;
}
}
}
}
fail();
}
@Test
void checkGetNavigationPropertyBindingsPath() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) {
for (final CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) {
if ("Roles".equals(binding.getPath()))
return;
}
}
}
fail();
}
@Test
void checkGetNavigationPropertyBindingsPathComplexType() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) {
for (final CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) {
if ("Address/AdministrativeDivision".equals(binding.getPath()))
return;
}
}
}
fail();
}
@Test
void checkGetNavigationPropertyBindingsPathComplexTypeNested() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlEntitySet> entitySets = container.getEdmItem().getEntitySets();
for (final CsdlEntitySet entitySet : entitySets) {
if (entitySet.getName().equals("BusinessPartners")) {
for (final CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) {
if ("AdministrativeInformation/Created/User".equals(binding.getPath()))
return;
}
}
}
fail();
}
@Test
void checkGetNoFunctionImportIfBound() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlFunctionImport> functionImports = container.getEdmItem().getFunctionImports();
for (final CsdlFunctionImport functionImport : functionImports) {
if (functionImport.getName().equals("CountRoles")) {
fail("Bound function must not generate a function import");
}
}
}
@Test
void checkGetNoFunctionImportIfUnboundHasImportFalse() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlFunctionImport> functionImports = container.getEdmItem().getFunctionImports();
for (final CsdlFunctionImport functionImport : functionImports) {
if (functionImport.getName().equals("max")) {
fail("UnBound function must not generate a function import if not annotated");
}
}
}
@Test
void checkGetNoFunctionImportForJavaBasedFunction() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlFunctionImport> functionImports = container.getEdmItem().getFunctionImports();
for (final CsdlFunctionImport functionImport : functionImports) {
if ("Sum".equals(functionImport.getName()))
return;
System.out.println(functionImport.getName());
}
fail("Import not found");
}
@Test
void checkGetFunctionImportIfUnboundHasImportTrue() throws ODataJPAModelException {
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlFunctionImport> functionImports = container.getEdmItem().getFunctionImports();
for (final CsdlFunctionImport functionImport : functionImports) {
if (functionImport.getName().equals("Olingo V4 ")) {
fail("UnBound function must be generate a function import is annotated");
}
}
}
@Test
void checkAnnotationSet() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new PostProcessorSetIgnore());
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final List<CsdlAnnotation> act = container.getEdmItem().getAnnotations();
assertEquals(1, act.size());
assertEquals("Capabilities.AsynchronousRequestsSupported", act.get(0).getTerm());
}
@Test
void checkReturnEntitySetBasedOnInternalEntityType() throws ODataJPAModelException {
final IntermediateEntityType<BestOrganization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType("BestOrganization"), schema);
final IntermediateEntityContainer container = new IntermediateEntityContainer(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schemas, annotationInfo);
final JPAElement act = container.getEntitySet(et);
assertNotNull(act);
assertEquals("BestOrganizations", act.getExternalName());
}
private static class PostProcessorSetIgnore implements JPAEdmMetadataPostProcessor {
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
if (jpaManagedTypeClassName.equals(
"com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) {
if (property.getInternalName().equals("communicationData")) {
property.setIgnore(true);
}
}
}
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {}
@Override
public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {}
@Override
public void processEntityContainer(final IntermediateEntityContainerAccess container) {
final CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false");
final CsdlAnnotation annotation = new CsdlAnnotation();
annotation.setExpression(mimeType);
annotation.setTerm("Capabilities.AsynchronousRequestsSupported");
final List<CsdlAnnotation> annotations = new ArrayList<>();
annotations.add(annotation);
container.addAnnotations(annotations);
}
}
@SuppressWarnings("unchecked")
private <T> EntityType<T> getEntityType(final String typeName) {
for (final EntityType<?> entityType : etList) {
if (entityType.getJavaType().getSimpleName().equals(typeName)) {
return (EntityType<T>) entityType;
}
}
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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAApiVersionProviderTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAApiVersionProviderTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import jakarta.persistence.EntityManagerFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class JPAApiVersionProviderTest {
private JPAApiVersionProvider.Builder builder;
private EntityManagerFactory emf;
private JPAEdmMetadataPostProcessor postProcessor;
@BeforeEach
void setup() {
emf = mock(EntityManagerFactory.class);
postProcessor = mock(JPAEdmMetadataPostProcessor.class);
builder = JPAApiVersionProvider.with();
}
@Test
void testBuilderSetIdThrowsNullPointerExceptionOnNull() {
assertThrows(NullPointerException.class, () -> builder.setId(null));
}
@Test
void testGetIdReturnsSetValue() throws ODataJPAModelException {
final var cut = builder.setId("V1").setEntityManagerFactory(emf).build();
assertEquals("V1", cut.getId());
}
@Test
void testBuilderThrowsExceptionOnMissingId() {
assertThrows(ODataJPAModelException.class, () -> builder.setEntityManagerFactory(emf).build());
}
@Test
void testBuilderSetEntityManagerFactoryThrowsNullPointerExceptionOnNull() {
assertThrows(NullPointerException.class, () -> builder.setEntityManagerFactory(null));
}
@Test
void testBuilderThrowsExceptionOnMissingEntityManagerFactory() {
assertThrows(ODataJPAModelException.class, () -> builder.setId("V1").build());
}
@Test
void testGetEntityManagerFactoryReturnsSetValue() throws ODataJPAModelException {
final var cut = builder.setId("V1").setEntityManagerFactory(emf).build();
assertEquals(emf, cut.getEntityManagerFactory());
}
@Test
void testGetTypePackageReturnsSetValue() throws ODataJPAModelException {
final var packageNames = new String[] { "com.test.action", "com.test.enum" };
final var cut = builder.setId("V1").setEntityManagerFactory(emf)
.setTypePackage(packageNames)
.build();
assertEquals(packageNames, cut.getPackageNames());
}
@Test
void testGetTypePackageReturnsEmptyArrayIfNotProvided() throws ODataJPAModelException {
final var cut = builder.setId("V1").setEntityManagerFactory(emf).build();
assertEquals(0, cut.getPackageNames().length);
}
@Test
void testGetRequestMappingPathReturnsSetValue() throws ODataJPAModelException {
final var cut = builder.setId("V1").setEntityManagerFactory(emf)
.setRequestMappingPath("/test/v1")
.build();
assertEquals("/test/v1", cut.getRequestMappingPath());
}
@Test
void testGetMetadataPostProcessorReturnsSetValue() throws ODataJPAModelException {
final var cut = builder.setId("V1").setEntityManagerFactory(emf)
.setMetadataPostProcessor(postProcessor)
.build();
assertEquals(postProcessor, cut.getMetadataPostProcessor());
}
@Test
void testGetMetadataPostProcessorReturnsDefaultIfNotProvided() throws ODataJPAModelException {
final var cut = builder.setId("V1").setEntityManagerFactory(emf).build();
assertNotNull(cut.getMetadataPostProcessor());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateModelElementTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateModelElementTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmItem;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class IntermediateModelElementTest {
private IntermediateModelElementImpl cut;
private IntermediateAnnotationInformation annotationInfo;
static Stream<Arguments> boxPrimitive() {
return Stream.of(
arguments(int.class, Integer.class),
arguments(Integer.class, Integer.class),
arguments(long.class, Long.class),
arguments(Long.class, Long.class),
arguments(short.class, Short.class),
arguments(Short.class, Short.class),
arguments(float.class, Float.class),
arguments(Float.class, Float.class),
arguments(double.class, Double.class),
arguments(Double.class, Double.class),
arguments(byte.class, Byte.class),
arguments(Byte.class, Byte.class),
arguments(boolean.class, Boolean.class),
arguments(Boolean.class, Boolean.class),
arguments(char.class, Character.class),
arguments(Character.class, Character.class));
}
@BeforeEach
void setup() {
cut = new IntermediateModelElementImpl(new JPADefaultEdmNameBuilder("Dummy"), "Test", annotationInfo);
}
@ParameterizedTest
@MethodSource("boxPrimitive")
void checkBoxPrimitive(final Class<?> type, final Class<?> result) {
assertEquals(result, cut.boxPrimitive(type));
}
@Test
void checkToString() {
assertTrue(cut.toString().contains("Test"));
}
@Test
void checkFindModelElementByEdmItemReturnsNull() {
assertNull(cut.findModelElementByEdmItem("Willi", new HashMap<>()));
}
@Test
void checkAsUserGroupRestrictedReturnsThis() throws ODataJPAModelException {
assertEquals(cut, cut.asUserGroupRestricted(List.of("Willi")));
}
private static class IntermediateModelElementImpl extends IntermediateModelElement {
public IntermediateModelElementImpl(final JPADefaultEdmNameBuilder nameBuilder, final String internalName,
final IntermediateAnnotationInformation annotationInfo) {
super(nameBuilder, internalName, annotationInfo);
}
@Override
protected void lazyBuildEdmItem() throws ODataJPAModelException {
// DO nothing
}
@Override
CsdlAbstractEdmItem getEdmItem() throws ODataJPAModelException {
return null;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/ODataActionKeyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/ODataActionKeyTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlAction;
import org.apache.olingo.commons.api.edm.provider.CsdlParameter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class ODataActionKeyTest {
private static final String TYPE_NAME = "Person";
private static final String NAMESPACE = "Punit";
private static final String ACTION_NAME = "Test";
private IntermediateOperation operation;
private CsdlAction csdl;
private ODataActionKey cut;
@BeforeEach
void setup() throws ODataJPAModelException {
csdl = mock(CsdlAction.class);
operation = createBoundOperation(csdl, ACTION_NAME);
cut = new ODataActionKey(operation);
}
private IntermediateOperation createBoundOperation(final CsdlAction csdlAction, final String actionName)
throws ODataJPAModelException {
final IntermediateOperation operation = mock(IntermediateOperation.class);
final List<CsdlParameter> parameters = new ArrayList<>();
final CsdlParameter parameter = mock(CsdlParameter.class);
parameters.add(parameter);
when(operation.getExternalName()).thenReturn(actionName);
when(operation.getEdmItem()).thenReturn(csdlAction);
when(operation.isBound()).thenReturn(true);
when(csdlAction.getParameters()).thenReturn(parameters);
when(parameter.getTypeFQN()).thenReturn(new FullQualifiedName(NAMESPACE, TYPE_NAME));
return operation;
}
@Test
void checkGetExternalName() {
assertEquals(ACTION_NAME, cut.getExternalName());
}
@Test
void checkGetBindingParameterType() {
final FullQualifiedName act = cut.getBindingParameterType();
assertEquals(NAMESPACE, act.getNamespace());
assertEquals(TYPE_NAME, act.getName());
}
@Test
void checkHasCode() {
assertNotEquals(0, cut.hashCode());
}
@Test
void checkEquals() throws ODataJPAModelException {
final IntermediateOperation other = createBoundOperation(mock(CsdlAction.class), "Other");
final IntermediateOperation other2 = createBoundOperation(mock(CsdlAction.class), "Other");
when(((CsdlAction) other2.getEdmItem()).getParameters().get(0).getTypeFQN())
.thenReturn(new FullQualifiedName("Dummy", TYPE_NAME));
assertEquals(cut, cut);
assertNotEquals(cut, "Test"); // NOSONAR
assertNotEquals(new ODataActionKey(other), cut);
assertNotEquals(new ODataActionKey(other2), cut);
}
@Test
void checkUnboundAction() throws ODataJPAModelException {
final IntermediateOperation operation = mock(IntermediateOperation.class);
final List<CsdlParameter> parameters = new ArrayList<>();
final CsdlParameter parameter = mock(CsdlParameter.class);
parameters.add(parameter);
when(operation.getExternalName()).thenReturn(ACTION_NAME);
when(operation.getEdmItem()).thenReturn(csdl);
when(operation.isBound()).thenReturn(false);
cut = new ODataActionKey(operation);
assertNull(cut.getBindingParameterType());
}
@Test
void checkToString() {
final String act = cut.toString();
assertTrue(act.contains(ACTION_NAME));
assertTrue(act.contains(TYPE_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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAProtectionInfo.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAProtectionInfo.java | /**
*
*/
package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author Oliver Grande
* Created: 14.02.2020
*
*/
class TestJPAProtectionInfo {
private JPAProtectionInfo cut;
@BeforeEach
void setup() {
cut = new JPAProtectionInfo(Arrays.asList("AdministrativeInformation/Created/By"), true);
}
@Test
void checkToStringContainsPath() {
assertNotNull(cut.toString());
assertTrue(cut.toString().contains("AdministrativeInformation/Created/By"));
}
@Test
void checkWildcardsTrue() {
assertTrue(cut.supportsWildcards());
}
@Test
void checkPathGetsReturned() {
final List<String> act = cut.getPath();
assertNotNull(act);
assertEquals(1, act.size());
assertEquals("AdministrativeInformation/Created/By", act.get(0));
}
@Test
void checkWildcardsReturnsFalseForInteger() {
assertFalse(cut.supportsWildcards(Integer.class));
}
@Test
void checkWildcardsReturnsFalseForDate() {
assertFalse(cut.supportsWildcards(LocalDate.class));
}
@Test
void checkWildcardsReturnsTrueForString() {
assertTrue(cut.supportsWildcards(String.class));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateDataBaseFunctionTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateDataBaseFunctionTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlParameter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeInformation;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.ChangeInformation;
import com.sap.olingo.jpa.processor.core.testmodel.DateConverter;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.util.Assertions;
class IntermediateDataBaseFunctionTest extends TestMappingRoot {
private TestHelper helper;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
}
@Test
void checkByEntityAnnotationCreate() {
assertNotNull(new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME), helper.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema));
}
@Test
void checkByEntityAnnotationGetName() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema);
assertEquals("CountRoles", function.getEdmItem().getName());
}
@Test
void checkByEntityAnnotationGetFunctionName() {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema);
assertEquals("COUNT_ROLES", function.getUserDefinedFunction());
}
@Test
void checkByEntityAnnotationInputParameterBound() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema);
final List<CsdlParameter> expInput = new ArrayList<>();
final CsdlParameter param = new CsdlParameter();
param.setName("Key");
param.setType(new FullQualifiedName("com.sap.olingo.jpa.BusinessPartner"));
param.setNullable(false);
expInput.add(param);
Assertions.assertListEquals(expInput, function.getEdmItem().getParameters(), CsdlParameter.class);
}
@Test
void checkByEntityAnnotationInputParameterBoundCompoundKey() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(helper.getEntityType(AdministrativeDivision.class), "SiblingsBound"),
AdministrativeDivision.class, helper.schema);
final List<CsdlParameter> expInput = new ArrayList<>();
final CsdlParameter param = new CsdlParameter();
param.setName("Key");
param.setType(new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision"));
param.setNullable(false);
expInput.add(param);
Assertions.assertListEquals(expInput, function.getEdmItem().getParameters(), CsdlParameter.class);
}
@Test
void checkByEntityAnnotationInputParameter2() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema);
final List<CsdlParameter> expInput = new ArrayList<>();
final CsdlParameter param = new CsdlParameter();
param.setName("Number");
param.setType(EdmPrimitiveTypeKind.Decimal.getFullQualifiedName());
param.setNullable(false);
param.setPrecision(32);
param.setScale(0);
expInput.add(param);
Assertions.assertListEquals(expInput, function.getEdmItem().getParameters(), CsdlParameter.class);
}
@Test
void checkByEntityAnnotationInputParameterIsEnumeration() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(helper.getEntityType(Person.class), "CheckRights"), BusinessPartner.class,
helper.schema);
assertNotNull(function.getEdmItem().getParameters());
assertEquals(2, function.getEdmItem().getParameters().size());
assertEquals(PUNIT_NAME + ".AccessRights", function.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
assertEquals("Edm.Int32", function.getEdmItem().getParameters().get(1).getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkByEntityAnnotationResultParameterIsEmpty() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema);
assertEquals(PUNIT_NAME + ".BusinessPartner", function.getEdmItem().getReturnType().getType());
}
@Test
void checkByEntityAnnotationIsBound() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema);
assertTrue(function.getEdmItem().isBound());
assertTrue(function.isBound());
assertEquals(PUNIT_NAME + ".BusinessPartner", function.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkByEntityAnnotationResultParameterSimple() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema);
assertEquals(EdmPrimitiveTypeKind.Boolean.getFullQualifiedName().getFullQualifiedNameAsString(), function
.getEdmItem()
.getReturnType().getType());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void checkByEntityAnnotationResultParameterIsEntity() throws ODataJPAModelException {
final IntermediateFunction function = (IntermediateFunction) new IntermediateFunctionFactory().create(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC");
assertEquals(PUNIT_NAME + ".Organization", function.getEdmItem().getReturnType().getType());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
void checkByEntityAnnotationResultParameterIsCollectionFalse() throws ODataJPAModelException {
IntermediateFunction function = (IntermediateFunction) new IntermediateFunctionFactory().create(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC");
assertTrue(function.getEdmItem().getReturnType().isCollection());
function = (IntermediateFunction) new IntermediateFunctionFactory().create(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper.getEntityType(BusinessPartner.class), helper.schema).get("IsPrime");
assertFalse(function.getEdmItem().getReturnType().isCollection());
}
@Test
void checkByEntityAnnotationResultParameterNotGiven() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema);
assertTrue(function.getEdmItem().getReturnType().isCollection());
assertEquals(PUNIT_NAME + ".BusinessPartner", function.getEdmItem().getReturnType().getType());
assertEquals(BusinessPartner.class, function.getResultParameter().getType());
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
void checkByEntityAnnotationResultParameterIsNullable() throws ODataJPAModelException {
IntermediateFunction function = (IntermediateFunction) new IntermediateFunctionFactory().create(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC");
assertTrue(function.getEdmItem().getReturnType().isNullable());
function = (IntermediateFunction) new IntermediateFunctionFactory().create(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper.getEntityType(BusinessPartner.class), helper.schema).get("IsPrime");
assertFalse(function.getEdmItem().getReturnType().isNullable());
}
@Test
void checkByEntityAnnotationResultParameterEnumerationType() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(helper.getEntityType(Person.class), "ReturnRights"), BusinessPartner.class,
helper.schema);
assertNotNull(function.getEdmItem().getReturnType());
assertEquals(PUNIT_NAME + ".AccessRights", function.getEdmItem().getReturnType().getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkReturnTypeEmbedded() throws ODataJPAModelException {
final EdmFunction function = mock(EdmFunction.class);
final EdmFunction.ReturnType returnType = mock(EdmFunction.ReturnType.class);
when(function.returnType()).thenReturn(returnType);
when(function.parameter()).thenReturn(new EdmParameter[0]);
when(returnType.type()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ChangeInformation.class;
}
});
final IntermediateFunction act = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
function,
BusinessPartner.class, helper.schema);
assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkReturnsEntitySetPathForBound() throws ODataJPAModelException {
final EdmFunction function = createBoundFunction();
final IntermediateFunction act = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
function, Person.class, helper.schema);
assertNotNull(act.getEdmItem());
assertTrue(act.getEdmItem().isBound());
assertEquals("Person/Roles", act.getEdmItem().getEntitySetPath());
}
@Test
void checkThrowsExceptionOnEntitySetGivenUnbound() {
final EdmFunction function = createBoundFunction();
when(function.isBound()).thenReturn(false);
final IntermediateFunction act = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
function, Person.class, helper.schema);
assertThrows(ODataJPAModelException.class, () -> act.getEdmItem());
}
@Test
void checkThrowsExceptionOnEntitySetGivenNoEntityReturnType() {
final EdmFunction function = createBoundFunction();
when(function.returnType().type()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return AdministrativeInformation.class;
}
});
final IntermediateFunction act = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
function, Person.class, helper.schema);
assertThrows(ODataJPAModelException.class, act::getEdmItem);
}
@Test
void checkReturnTypeUnknown() throws ODataJPAModelException {
final EdmFunction function = mock(EdmFunction.class);
final EdmFunction.ReturnType returnType = mock(EdmFunction.ReturnType.class);
when(function.returnType()).thenReturn(returnType);
when(function.parameter()).thenReturn(new EdmParameter[0]);
when(returnType.type()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return DateConverter.class;
}
});
IntermediateFunction act;
try {
act = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME), function, BusinessPartner.class,
helper.schema);
act.getEdmItem();
} catch (final ODataJPAModelException e) {
assertEquals(ODataJPAModelException.MessageKeys.FUNC_RETURN_TYPE_UNKNOWN.getKey(), e.getId());
return;
}
fail();
}
@Test
void checkGetGroupsReturnsGiven() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "max"), BusinessPartner.class, helper.schema);
assertEquals(List.of("Person"), function.getUserGroups());
}
@Test
void checkGetGroupsReturnsEmptyListIfNoProvided() throws ODataJPAModelException {
final IntermediateFunction function = new IntermediateDataBaseFunction(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper
.getStoredProcedure(
helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema);
assertTrue(function.getUserGroups().isEmpty());
}
private EdmFunction createBoundFunction() {
final EdmFunction function = mock(EdmFunction.class);
final EdmFunction.ReturnType returnType = mock(EdmFunction.ReturnType.class);
when(function.isBound()).thenReturn(true);
when(function.entitySetPath()).thenReturn("Person/Roles");
when(function.returnType()).thenReturn(returnType);
when(function.parameter()).thenReturn(new EdmParameter[0]);
when(returnType.type()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return BusinessPartnerRole.class;
}
});
return function;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateNavigationPropertyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateNavigationPropertyTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import jakarta.persistence.OneToMany;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.ManagedType;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlOnDelete;
import org.apache.olingo.commons.api.edm.provider.CsdlOnDeleteAction;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlReferentialConstraint;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.api.JPAJoinColumn;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtectedBy;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmVisibleFor;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
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.JPAJoinTable;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.util.AnnotationTestHelper;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.ExampleProperties;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.Terms;
import com.sap.olingo.jpa.metadata.odata.v4.general.Aliases;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCoreAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.errormodel.MissingCardinalityAnnotation;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AnnotationsParent;
import com.sap.olingo.jpa.processor.core.testmodel.AssociationOneToManyTarget;
import com.sap.olingo.jpa.processor.core.testmodel.AssociationOneToOneSource;
import com.sap.olingo.jpa.processor.core.testmodel.AssociationOneToOneTarget;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.ChangeInformation;
import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored;
import com.sap.olingo.jpa.processor.core.testmodel.EntityTypeOnly;
import com.sap.olingo.jpa.processor.core.testmodel.JoinComplex;
import com.sap.olingo.jpa.processor.core.testmodel.JoinSource;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData;
@Tag(value = "Model")
class IntermediateNavigationPropertyTest extends TestMappingRoot {
private IntermediateSchema schema;
private TestHelper helper;
private TestHelper errorHelper;
private IntermediateSchema errorSchema;
private JPAEdmMetadataPostProcessor processor;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateReferences reference;
@BeforeEach
void setup() throws ODataJPAModelException {
final Reflections reflections = mock(Reflections.class);
reference = mock(IntermediateReferences.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>(), reference);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class)));
schema = new IntermediateSchema(nameBuilder, emf.getMetamodel(), reflections, annotationInfo);
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
errorHelper = new TestHelper(errorEmf.getMetamodel(), ERROR_PUNIT);
errorSchema = new IntermediateSchema(errorNameBuilder, errorEmf.getMetamodel(), reflections, annotationInfo);
processor = mock(JPAEdmMetadataPostProcessor.class);
}
@Test
void checkNavigationPropertyCanBeCreated() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartner.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "roles");
final JPAAssociationAttribute act = new IntermediateNavigationProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
schema.getStructuredType(jpaAttribute), jpaAttribute, schema);
assertNotNull(act);
}
@Test
void checkGetName() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<BusinessPartner> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertEquals("Roles", property.getEdmItem().getName(), "Wrong name");
}
@Test
void checkGetNameIfSource() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(
helper.getEntityType(BusinessPartnerRole.class), "organization");
final IntermediateNavigationProperty<BusinessPartner> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertEquals("Organization", property.getEdmItem().getName(), "Wrong name");
}
@Test
void checkGetEdmType() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<BusinessPartner> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertEquals(PUNIT_NAME + ".BusinessPartnerRole", property.getEdmItem().getType(), "Wrong name");
}
@Test
void checkGetIgnoreFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<Object> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getStructuredType(jpaAttribute), jpaAttribute, schema);
assertFalse(property.ignore());
}
@Test
void checkGetIgnoreTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(DummyToBeIgnored.class),
"businessPartner");
final IntermediateNavigationProperty<Object> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getStructuredType(jpaAttribute), jpaAttribute, schema);
assertTrue(property.ignore());
}
@Test
void checkGetPropertyFacetsNullableTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<BusinessPartner> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertTrue(property.getEdmItem().isNullable());
}
@Test
void checkGetPropertyFacetsCollectionTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<BusinessPartner> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertTrue(property.getEdmItem().isCollection());
}
@Test
void checkGetPropertyOnDelete() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<BusinessPartner> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertEquals(CsdlOnDeleteAction.Cascade, property.getEdmItem().getOnDelete().getAction());
}
@Test
void checkGetPropertyFacetsNullableFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class),
"businessPartner");
final IntermediateNavigationProperty<BusinessPartnerRole> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema);
assertFalse(property.getEdmItem().isNullable());
}
@Test
void checkGetPropertyFacetsCollectionFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class),
"businessPartner");
final IntermediateNavigationProperty<BusinessPartnerRole> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema);
assertFalse(property.getEdmItem().isCollection());
}
@Test
void checkGetPropertyFacetsCollectionFalseOnToOne() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class),
"image");
final IntermediateNavigationProperty<Person> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(Person.class), jpaAttribute, schema);
assertFalse(property.getEdmItem().isCollection());
}
@Test
void checkGetJoinColumnsSize1OneToManyMapped() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartner.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "roles");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals(1, property.getJoinColumns().size());
final JPAJoinColumn act = property.getJoinColumns().get(0);
assertEquals("\"ID\"", act.getName());
assertEquals("\"BusinessPartnerID\"", act.getReferencedColumnName());
}
@Test
void checkGetJoinColumnsSize1OneToManyNotMapped() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartnerProtected.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "rolesProtected");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals(1, property.getJoinColumns().size());
final JPAJoinColumn act = property.getJoinColumns().get(0);
assertEquals("\"ID\"", act.getName());
assertEquals("\"BusinessPartnerID\"", act.getReferencedColumnName());
}
@Test
void checkGetPartnerAdmin_Parent() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(AdministrativeDivision.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "parent");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals("Children", property.getEdmItem().getPartner());
}
@Test
void checkGetPartnerAdmin_Children() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(AdministrativeDivision.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "children");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals("Parent", property.getEdmItem().getPartner());
}
@Test
void checkGetPartnerBP_Roles() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartner.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "roles");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals("BusinessPartner", property.getEdmItem().getPartner());
}
@Test
void checkGetPartnerRole_BP() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartnerRole.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals("Roles", property.getEdmItem().getPartner());
}
@Test
void checkGetJoinColumnFilledCompletely() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartner.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "roles");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
final JPAJoinColumn act = property.getJoinColumns().get(0);
assertEquals("\"ID\"", act.getName());
assertEquals("\"BusinessPartnerID\"", act.getReferencedColumnName());
}
@Test
void checkGetJoinColumnFilledCompletelyInvert() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartnerRole.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
final JPAJoinColumn act = property.getJoinColumns().get(0);
assertEquals("\"BusinessPartnerID\"", act.getName());
assertEquals("\"ID\"", act.getReferencedColumnName());
}
@Test
void checkGetJoinColumnsSize1ManyToOne() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(BusinessPartnerRole.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(et.getJavaType()), jpaAttribute, schema);
assertEquals(1, property.getJoinColumns().size());
final JPAJoinColumn act = property.getJoinColumns().get(0);
assertEquals("\"ID\"", act.getReferencedColumnName());
assertEquals("\"BusinessPartnerID\"", act.getName());
}
@Test
void checkGetJoinColumnsSize2ManyToOne() throws ODataJPAModelException {
final EmbeddableType<?> et = helper.getEmbeddableType(PostalAddressData.class);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, "administrativeDivision");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getComplexType(et.getJavaType()), jpaAttribute, schema);
final List<? extends JPAJoinColumn> columns = property.getJoinColumns();
assertEquals(3, columns.size());
}
@Test
void checkGetReferentialConstraintSize() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertTrue(property.isMapped());
assertEquals(1, property.getProperty().getReferentialConstraints().size());
}
@Test
void checkGetReferentialConstraintBuPaRole() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
final List<CsdlReferentialConstraint> constraints = property.getProperty().getReferentialConstraints();
for (final CsdlReferentialConstraint c : constraints) {
assertEquals("ID", c.getProperty());
assertEquals("BusinessPartnerID", c.getReferencedProperty());
}
}
@Test
void checkGetReferentialConstraintRoleBuPa() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class),
"businessPartner");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema);
final List<CsdlReferentialConstraint> constraints = property.getProperty().getReferentialConstraints();
for (final CsdlReferentialConstraint c : constraints) {
assertEquals("BusinessPartnerID", c.getProperty());
assertEquals("ID", c.getReferencedProperty());
}
}
@Test
void checkGetReferentialConstraintViaEmbeddedId() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class),
"allDescriptions");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(AdministrativeDivision.class), jpaAttribute, schema);
final List<CsdlReferentialConstraint> constraints = property.getProperty().getReferentialConstraints();
assertEquals(3, constraints.size());
for (final CsdlReferentialConstraint c : constraints) {
assertEquals(c.getReferencedProperty(), c.getProperty());
}
}
@Test
void checkGetReferentialConstraintNotCreatedIfPropertyToBeIgnored() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(EntityTypeOnly.class),
"generalSettings");
final IntermediateNavigationProperty<EntityTypeOnly> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(EntityTypeOnly.class), jpaAttribute, schema);
final List<CsdlReferentialConstraint> constraints = property.getProperty().getReferentialConstraints();
assertTrue(constraints.isEmpty());
}
@Test
void checkPostProcessorCalled() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(processor);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
BusinessPartner.class), "roles");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
property.getEdmItem();
verify(processor, atLeastOnce()).processNavigationProperty(property, BUPA_CANONICAL_NAME);
}
@Test
void checkPostProcessorAnnotationAdded() throws ODataJPAModelException {
final PostProcessorSetName postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"roles");
final IntermediateNavigationProperty<?> cut = new IntermediateNavigationProperty<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertEquals(1L, cut.getEdmItem().getAnnotations().stream().filter(a -> a.getTerm().equals("Immutable")).count());
}
@Test
void checkPostProcessorSetOnDelete() throws ODataJPAModelException {
final PostProcessorOneDelete postProcessorDouble = new PostProcessorOneDelete();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class),
"children");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(AdministrativeDivision.class), jpaAttribute, schema);
assertEquals(CsdlOnDeleteAction.None, property.getProperty().getOnDelete().getAction());
}
@Test
void checkGetJoinTable() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class),
"supportedOrganizations");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertNotNull(property.getJoinTable());
}
@Test
void checkGetJoinTableMappedBy() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Organization.class),
"supportEngineers");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
property.getEdmItem();
assertNotNull(property.getJoinTable());
final JPAJoinTable act = property.getJoinTable();
assertEquals(1, act.getJoinColumns().size());
assertEquals("ID", act.getJoinColumns().get(0).getLeftPath().getAlias());
assertEquals("OrganizationID", act.getJoinColumns().get(0).getRightPath().getAlias());
}
@Test
void checkGetJoinTableName() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class),
"supportedOrganizations");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME),
schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertEquals("\"OLINGO\".\"SupportRelationship\"", property.getJoinTable().getTableName());
}
@Test
void checkGetNullIfNoJoinTableGiven() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class),
"parent");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertNull(property.getJoinTable());
}
@Test
void checkGetJoinTableJoinColumns() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class),
"supportedOrganizations");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME),
schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertFalse(property.getJoinColumns().isEmpty());
}
@Test
void checkGetJoinTableEntityType() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class),
"supportedOrganizations");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME),
schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertNotNull(property.getJoinTable().getEntityType());
}
@Test
void checkGetJoinTableJoinColumnsNotMapped() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(JoinSource.class),
"oneToMany");
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), jpaAttribute, schema);
assertFalse(property.getJoinColumns().isEmpty());
assertNotNull(property.getJoinTable());
final IntermediateJoinTable act = (IntermediateJoinTable) property.getJoinTable();
for (final JPAOnConditionItem item : act.getJoinColumns()) {
assertNotNull(item.getLeftPath());
assertNotNull(item.getRightPath());
}
for (final JPAOnConditionItem item : act.getInverseJoinColumns()) {
assertNotNull(item.getLeftPath());
assertNotNull(item.getRightPath());
}
}
@Test
void checkGetJoinTableJoinColumnsMapped() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Organization.class),
"supportEngineers");
final IntermediateNavigationProperty<?> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(BusinessPartner.class), jpaAttribute, schema);
assertFalse(property.getJoinColumns().isEmpty());
}
@Test
void checkGetJoinTableJoinColumnsMissingInverse() throws ODataJPAModelException {
final EmbeddableType<JoinComplex> jpaEmbeddable = helper.getEmbeddableType(JoinComplex.class);
final IntermediateStructuredType<?> property = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), jpaEmbeddable, schema);
final JPAAssociationAttribute association = property.getAssociation("oneToManyComplex");
final JPAAssociationPath path = association.getPath();
assertNotNull(path.getJoinTable());
assertEquals(1, path.getJoinTable().getInverseJoinColumns().size());
assertNotNull(path.getJoinTable().getInverseJoinColumns().get(0).getLeftPath());
assertNotNull(path.getJoinTable().getInverseJoinColumns().get(0).getRightPath());
// path.getJoinTable().getJoinColumns()
}
@Test
void checkGetJoinTableJoinViaComplex() throws ODataJPAModelException {
final EntityType<JoinSource> jpaEntity = helper.getEntityType(JoinSource.class);
final IntermediateEntityType<JoinSource> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaEntity, schema);
et.lazyBuildEdmItem();
final JPAAssociationPath a = et.getAssociationPath("Complex/OneToManyComplex");
assertNotNull(a.getJoinTable());
assertNotNull(a.getJoinTable().getJoinColumns());
assertEquals(1, a.getJoinTable().getJoinColumns().size());
assertFalse(a.getInverseLeftJoinColumnsList().isEmpty());
assertEquals(1, a.getJoinTable().getInverseJoinColumns().size());
assertEquals("\"TargetID\"", a.getJoinTable().getInverseJoinColumns().get(0).getLeftPath().getDBFieldName());
}
@Test
void checkGetConverterReturnsNull() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertNull(property.getConverter());
}
@Test
void checkGetRawConverterReturnsNull() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertNull(property.getRawConverter());
}
@Test
void checkGetDbTypeReturnsNull() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertNull(property.getDbType());
}
@Test
void checkGetCalculatorConstructorReturnsNull() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertNull(property.getCalculatorConstructor());
}
@Test
void checkGetEdmTypeReturnsNull() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertNull(property.getEdmType());
}
@Test
void checkHasProtectionReturnsFalse() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
assertFalse(property.hasProtection());
}
@Test
void checkIsAssociationReturnsTrue() throws ODataJPAModelException {
final IntermediateNavigationProperty<JoinSource> property = new IntermediateNavigationProperty<>(
new JPADefaultEdmNameBuilder(
PUNIT_NAME), schema.getEntityType(JoinSource.class), createDummyAttribute(), schema);
| 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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAOnConditionItemImpl.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAOnConditionItemImpl.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
class TestJPAOnConditionItemImpl {
private JPAOnConditionItemImpl cut;
@Test
void checkThrowsExceptionOnMissingLeft() {
final JPAPath rightAttribute = mock(JPAPath.class);
final NullPointerException act = assertThrows(NullPointerException.class,
() -> new JPAOnConditionItemImpl(null, rightAttribute));
assertEquals("ON condition left attribute is null / not found.", act.getMessage());
}
@Test
void checkThrowsExceptionOnMissingRight() {
final JPAPath leftAttribute = mock(JPAPath.class);
final NullPointerException act = assertThrows(NullPointerException.class,
() -> new JPAOnConditionItemImpl(leftAttribute, null));
assertEquals("ON condition right attribute is null / not found.", act.getMessage());
}
@Test
void checkReturnProvidedValues() {
final JPAPath leftAttribute = mock(JPAPath.class);
final JPAPath rightAttribute = mock(JPAPath.class);
cut = new JPAOnConditionItemImpl(leftAttribute, rightAttribute);
assertEquals(leftAttribute, cut.getLeftPath());
assertEquals(rightAttribute, cut.getRightPath());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEntityTypeTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEntityTypeTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.PROPERTY_REQUIRED_UNKNOWN;
import static com.sap.olingo.jpa.processor.core.util.Assertions.assertListEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import jakarta.persistence.Table;
import jakarta.persistence.metamodel.EntityType;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlNavigationProperty;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression;
import org.apache.olingo.server.api.uri.UriResourceProperty;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataNavigationPath;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataPathNotFoundException;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataPropertyPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEtagValidator;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAInheritanceType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.util.AnnotationTestHelper;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.ExampleProperties;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.Terms;
import com.sap.olingo.jpa.metadata.odata.v4.general.Aliases;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCoreAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.errormodel.TeamWithTransientError;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription;
import com.sap.olingo.jpa.processor.core.testmodel.AnnotationsParent;
import com.sap.olingo.jpa.processor.core.testmodel.AssociationOneToOneSource;
import com.sap.olingo.jpa.processor.core.testmodel.BestOrganization;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole;
import com.sap.olingo.jpa.processor.core.testmodel.Collection;
import com.sap.olingo.jpa.processor.core.testmodel.CollectionDeep;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUser;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUserQueryExtension;
import com.sap.olingo.jpa.processor.core.testmodel.DeepProtectedExample;
import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored;
import com.sap.olingo.jpa.processor.core.testmodel.EmptyQueryExtensionProvider;
import com.sap.olingo.jpa.processor.core.testmodel.EntityTypeOnly;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinAccount;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinCompoundSub;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinCompoundSuper;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinCurrentAccount;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinLockedSavingAccount;
import com.sap.olingo.jpa.processor.core.testmodel.InheritanceByJoinSavingAccount;
import com.sap.olingo.jpa.processor.core.testmodel.JoinRelation;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.testmodel.PersonDeepProtected;
import com.sap.olingo.jpa.processor.core.testmodel.PersonDeepProtectedHidden;
import com.sap.olingo.jpa.processor.core.testmodel.PersonImage;
import com.sap.olingo.jpa.processor.core.testmodel.RestrictedEntityUnrestrictedSource;
import com.sap.olingo.jpa.processor.core.testmodel.SalesTeam;
import com.sap.olingo.jpa.processor.core.testmodel.Singleton;
import com.sap.olingo.jpa.processor.core.testmodel.TransientRefComplex;
import com.sap.olingo.jpa.processor.core.testmodel.TransientRefIgnore;
import com.sap.olingo.jpa.processor.core.testmodel.UnionMembership;
import com.sap.olingo.jpa.processor.core.util.TestDataConstants;
class IntermediateEntityTypeTest extends TestMappingRoot {
private IntermediateSchema schema;
private IntermediateSchema errorSchema;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateReferences references;
@BeforeEach
void setup() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
final Reflections reflections = mock(Reflections.class);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class)));
references = mock(IntermediateReferences.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>(), references);
schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), reflections,
annotationInfo);
errorSchema = new IntermediateSchema(new JPADefaultEdmNameBuilder(ERROR_PUNIT), errorEmf.getMetamodel(),
reflections, annotationInfo);
}
@Test
void checkEntityTypeCanBeCreated() {
assertNotNull(new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema));
}
@Test
void checkEntityTypeIgnoreSet() throws ODataJPAModelException {
final IntermediateStructuredType<DummyToBeIgnored> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(DummyToBeIgnored.class), schema);
et.getEdmItem();
assertTrue(et.ignore());
}
@Test
void checkGetAllProperties() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals(TestDataConstants.NO_DEC_ATTRIBUTES_BUSINESS_PARTNER.value, et.getEdmItem()
.getProperties()
.size(), "Wrong number of entities");
}
@Test
void checkGetPropertyByNameNotNull() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertNotNull(et.getEdmItem().getProperty("Type"));
}
@Test
void checkGetPropertyByNameCorrectEntity() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals("Type", et.getEdmItem().getProperty("Type").getName());
}
@Test
void checkGetPropertyByNameCorrectEntityID() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals("ID", et.getEdmItem().getProperty("ID").getName());
}
@Test
void checkGetPathByNameCorrectEntityID() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals("ID", et.getPath("ID").getLeaf().getExternalName());
}
@Test
void checkGetPathByNameIgnore() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertNull(et.getPath("CustomString2"));
}
@Test
void checkGetDescriptionPropertyByName() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertNotNull(et.getAttribute("locationName"));
assertNotNull(et.getBaseType().getEdmItem().getProperty("LocationName"));
}
@Test
void checkGetDescriptionPropertyFromComplexByName() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertTrue(et.getAttribute("address").isPresent());
assertTrue(et.getAttribute("address").get().getStructuredType().getAttribute("countryName").isPresent());
// Trigger cascade of building the edm items
assertNotNull(et.getEdmItem().getProperty("Address"));
final IntermediateDescriptionProperty act = (IntermediateDescriptionProperty) et.getAttribute("address").get()
.getStructuredType().getAttribute("countryName").get();
assertNotNull(act.getDescriptionAttribute());
assertNotNull(act.getTargetEntity());
assertNotNull(act.getLocaleFieldName());
assertNotNull(act.getFixedValueAssignment());
}
@Test
void checkGetPathByNameIgnoreComplexType() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertNull(et.getPath("Address/RegionCodePublisher"));
}
@Test
void checkGetInheritedAttributeByNameCorrectEntityID() throws ODataJPAModelException {
final IntermediateStructuredType<Person> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
getEntityType(Person.class), schema);
assertEquals("ID", et.getPath("ID").getLeaf().getExternalName());
}
@Test
void checkGetAllNavigationProperties() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals(1, et.getEdmItem().getNavigationProperties().size(), "Wrong number of entities");
}
@Test
void checkGetNavigationPropertyByNameNotNull() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertNotNull(et.getEdmItem().getNavigationProperty("Roles"));
}
@Test
void checkGetNavigationPropertyByNameCorrectEntity() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals("Roles", et.getEdmItem().getNavigationProperty("Roles").getName());
}
@Test
void checkGetAssociationOfComplexTypeByNameCorrectEntity() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals("Address/AdministrativeDivision", et.getAssociationPath("Address/AdministrativeDivision").getAlias());
}
@Test
void checkGetAssociationOfComplexTypeByNameJoinColumns() throws ODataJPAModelException {
int actCount = 0;
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
for (final JPAOnConditionItem item : et.getAssociationPath("Address/AdministrativeDivision").getJoinColumnsList()) {
if (item.getLeftPath().getAlias().equals("Address/Region")) {
assertEquals("DivisionCode", item.getRightPath().getAlias());
actCount++;
}
if (item.getLeftPath().getAlias().equals("Address/RegionCodeID")) {
assertEquals("CodeID", item.getRightPath().getAlias());
actCount++;
}
if (item.getLeftPath().getAlias().equals("Address/RegionCodePublisher")) {
assertEquals("CodePublisher", item.getRightPath().getAlias());
actCount++;
}
}
assertEquals(3, actCount, "Not all join columns found");
}
@Test
void checkGetAssociationOfMappedByWithVirtualProperty() throws ODataJPAModelException {
final IntermediateStructuredType<AssociationOneToOneSource> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AssociationOneToOneSource.class), schema);
final JPAAssociationPath act = et.getAssociationPath("DefaultTarget");
assertEquals(1, act.getJoinColumnsList().size());
final JPAOnConditionItem actColumn = act.getJoinColumnsList().get(0);
assertEquals("ID", actColumn.getRightPath().getAlias());
assertEquals("Defaulttarget_id", actColumn.getLeftPath().getAlias());
}
@Test
void checkGetPropertiesSkipIgnored() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals(TestDataConstants.NO_DEC_ATTRIBUTES_BUSINESS_PARTNER.value - 1, et.getEdmItem()
.getProperties().size(), "Wrong number of entities");
}
@Test
void checkGetIsAbstract() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertTrue(et.getEdmItem().isAbstract());
}
@Test
void checkGetIsNotAbstract() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertFalse(et.getEdmItem().isAbstract());
}
@Test
void checkGetHasBaseType() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertEquals(PUNIT_NAME + ".BusinessPartner", et.getEdmItem().getBaseType());
}
@Test
void checkGetKeyProperties() throws ODataJPAModelException {
final IntermediateEntityType<BusinessPartnerRole> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartnerRole.class), schema);
assertEquals(2, et.getEdmItem().getKey().size(), "Wrong number of key properties");
}
@Test
void checkGetAllAttributes() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartnerRole> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(BusinessPartnerRole.class), schema);
assertEquals(2, et.getPathList().size(), "Wrong number of entities");
}
@Test
void checkGetAllAttributesWithBaseType() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
final int exp =
TestDataConstants.NO_ATTRIBUTES_BUSINESS_PARTNER.value
+ TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS.value
+ TestDataConstants.NO_ATTRIBUTES_COMMUNICATION_DATA.value
+ 2 * TestDataConstants.NO_ATTRIBUTES_CHANGE_INFO.value
+ TestDataConstants.NO_ATTRIBUTES_ORGANIZATION.value;
assertEquals(exp, et.getPathList().size(), "Wrong number of entities");
}
@Test
void checkGetAllAttributesWithBaseTypeFields() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertNotNull(et.getPath("Type"));
assertNotNull(et.getPath("Name1"));
assertNotNull(et.getPath("Address" + JPAPath.PATH_SEPARATOR + "Region"));
assertNotNull(et.getPath("AdministrativeInformation" + JPAPath.PATH_SEPARATOR
+ "Created" + JPAPath.PATH_SEPARATOR + "By"));
}
@Test
void checkGetAllAttributeIDWithBaseType() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertEquals("ID", et.getPath("ID").getAlias());
}
@Test
void checkGetKeyAttributeFromEmbeddedId() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
assertTrue(et.getAttribute("codePublisher").isPresent());
assertEquals("CodePublisher", et.getAttribute("codePublisher").get().getExternalName());
}
@Test
void checkGetKeyAttributeFromEmbeddedIdFromUriResource() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
final UriResourceProperty uriResourceItem = mock(UriResourceProperty.class);
final EdmProperty edmProperty = mock(EdmProperty.class);
when(uriResourceItem.getProperty()).thenReturn(edmProperty);
when(edmProperty.getName()).thenReturn("CodePublisher");
final Optional<JPAAttribute> act = et.getAttribute(uriResourceItem);
assertTrue(act.isPresent());
assertEquals("CodePublisher", act.get().getExternalName());
}
@Test
void checkGetKeyWithBaseType() throws ODataJPAModelException {
final IntermediateEntityType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertEquals(1, et.getKey().size());
}
@Test
void checkGetKeyFromMappedSuperclass() throws ODataJPAModelException {
final IntermediateEntityType<SalesTeam> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(SalesTeam.class), schema);
assertEquals(1, et.getKey().size());
}
@Test
void checkEmbeddedIdResolvedProperties() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
assertEquals(5, et.getEdmItem().getProperties().size());
}
@Test
void checkEmbeddedIdResolvedKey() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
assertEquals(4, et.getEdmItem().getKey().size());
}
@Test
void checkEmbeddedIdResolvedKeyInternal() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
assertEquals(4, et.getKey().size());
}
@Test
void checkEmbeddedIdResolvedKeyCorrectOrder() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
assertEquals("CodePublisher", et.getEdmItem().getKey().get(0).getName());
assertEquals("CodeID", et.getEdmItem().getKey().get(1).getName());
assertEquals("DivisionCode", et.getEdmItem().getKey().get(2).getName());
assertEquals("Language", et.getEdmItem().getKey().get(3).getName());
}
@Test
void checkCompoundResolvedKeyCorrectOrder() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivision> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivision.class), schema);
assertEquals("CodePublisher", et.getKey().get(0).getExternalName());
assertEquals("CodeID", et.getKey().get(1).getExternalName());
assertEquals("DivisionCode", et.getKey().get(2).getExternalName());
}
@Test
void checkEmbeddedIdResolvedPath() throws ODataJPAModelException {
final JPAStructuredType et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(
AdministrativeDivisionDescription.class), schema);
assertEquals(5, et.getPathList().size());
}
@Test
void checkEmbeddedIdResolvedPathCodeId() throws ODataJPAModelException {
final JPAStructuredType et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(
AdministrativeDivisionDescription.class), schema);
assertEquals(2, et.getPath("CodeID").getPath().size());
}
@Test
void checkEmbeddedIdResolvedKeyPath() throws ODataJPAModelException {
final JPAEntityType et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(
AdministrativeDivisionDescription.class), schema);
assertEquals(1, et.getKeyPath().size());
}
@Test
void checkEmbeddedIdInheritedWithMappingKeyPath() throws ODataJPAModelException {
final JPAEntityType et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(
InheritanceByJoinCompoundSub.class), schema);
assertEquals(3, et.getKey().size());
var divisionKey = et.getKey().stream().filter(key -> "DivisionCode".equals(key.getExternalName())).findFirst();
assertNotNull(divisionKey);
assertEquals("\"PartCode\"", ((IntermediateSimpleProperty) divisionKey.get()).dbFieldName);
assertEquals(3, et.getKeyPath().size());
var divisionCode = et.getKeyPath().stream().filter(path -> "DivisionCode".equals(path.getAlias()))
.findFirst();
assertTrue(divisionCode.isPresent());
assertEquals("\"PartCode\"", divisionCode.get().getDBFieldName());
}
@Test
void checkInheritedWithMappingKeyPath() throws ODataJPAModelException {
final JPAEntityType et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(
InheritanceByJoinLockedSavingAccount.class), schema);
assertEquals(1, et.getKey().size());
var key = et.getKey().get(0);
assertNotNull(key);
assertEquals("\"AccountId\"", ((IntermediateSimpleProperty) key).dbFieldName);
assertEquals(1, et.getKeyPath().size());
var keyPath = et.getKeyPath().get(0);
assertEquals("\"AccountId\"", keyPath.getDBFieldName());
}
@Test
void checkHasStreamNoProperties() throws ODataJPAModelException {
final IntermediateEntityType<PersonImage> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(PersonImage.class), schema);
assertEquals(2, et.getEdmItem().getProperties().size());
}
@Test
void checkHasStreamTrue() throws ODataJPAModelException {
final IntermediateEntityType<PersonImage> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(PersonImage.class), schema);
assertTrue(et.getEdmItem().hasStream());
}
@Test
void checkHasStreamFalse() throws ODataJPAModelException {
final IntermediateEntityType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertFalse(et.getEdmItem().hasStream());
}
@Test
void checkHasEtagTrue() throws ODataJPAModelException {
final IntermediateEntityType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertTrue(et.hasEtag());
}
@Test
void checkHasEtagTrueIfInherited() throws ODataJPAModelException {
final IntermediateEntityType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertTrue(et.hasEtag());
}
@Test
void checkHasEtagFalse() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivision> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AdministrativeDivision.class), schema);
assertFalse(et.hasEtag());
}
@Test
void checkIgnoreIfAsEntitySet() {
final IntermediateEntityType<BestOrganization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BestOrganization.class), schema);
assertTrue(et.ignore());
}
@Test
void checkEtagValidatorNullWithoutEtag() throws ODataJPAModelException {
final IntermediateEntityType<AdministrativeDivision> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AdministrativeDivision.class), schema);
assertNull(et.getEtagValidator());
}
@Test
void checkEtagValidatorIsStrongForLong() throws ODataJPAModelException {
final IntermediateEntityType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals(JPAEtagValidator.STRONG, et.getEtagValidator());
}
@Test
void checkEtagValidatorIsWeakForTimestamp() throws ODataJPAModelException {
final IntermediateEntityType<DeepProtectedExample> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(DeepProtectedExample.class), schema);
assertEquals(JPAEtagValidator.WEAK, et.getEtagValidator());
}
@Test
void checkEtagValidatorIsInherited() throws ODataJPAModelException {
final IntermediateEntityType<Person> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Person.class), schema);
assertEquals(JPAEtagValidator.STRONG, et.getEtagValidator());
}
@Test
void checkAnnotationSet() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new PostProcessorSetIgnore());
final IntermediateEntityType<PersonImage> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(PersonImage.class), schema);
final List<CsdlAnnotation> act = et.getEdmItem().getAnnotations();
assertEquals(1, act.size());
assertEquals("Core.AcceptableMediaTypes", act.get(0).getTerm());
}
@Test
void checkGetPropertyByDBFieldName() throws ODataJPAModelException {
final IntermediateStructuredType<BusinessPartner> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
assertEquals("Type", et.getPropertyByDBField("\"Type\"").getExternalName());
}
@Test
void checkGetPropertyByDBFieldNameFromSuperType() throws ODataJPAModelException {
final IntermediateStructuredType<Organization> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Organization.class), schema);
assertEquals("Type", et.getPropertyByDBField("\"Type\"").getExternalName());
}
@Test
void checkGetPropertyByDBFieldNameFromEmbedded() throws ODataJPAModelException {
final IntermediateStructuredType<AdministrativeDivisionDescription> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(AdministrativeDivisionDescription.class), schema);
assertEquals("CodeID", et.getPropertyByDBField("\"CodeID\"").getExternalName());
}
@Test
void checkAllPathContainsComplexCollection() throws ODataJPAModelException {
final IntermediateStructuredType<Collection> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Collection.class), schema);
final List<JPAPath> act = et.getPathList();
assertEquals(13, act.size());
assertNotNull(et.getPath("Complex/Address"));
assertTrue(et.getPath("Complex/Address").getLeaf().isCollection());
final IntermediateCollectionProperty<?> actIntermediate = (IntermediateCollectionProperty<?>) et.getPath(
"Complex/Address").getLeaf();
assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType);
assertEquals(2, actIntermediate.asAssociation().getPath().size());
for (final JPAPath p : act) {
if (p.getPath().size() > 1
&& p.getPath().get(0).getExternalName().equals("Complex")
&& p.getPath().get(1).getExternalName().equals("Address")) {
assertTrue(p.getPath().get(1) instanceof IntermediateCollectionProperty);
final IntermediateCollectionProperty<?> actProperty = (IntermediateCollectionProperty<?>) p.getPath().get(1);
assertNotNull(actProperty.asAssociation());
assertEquals(et, actProperty.asAssociation().getSourceType());
break;
}
}
}
@Test
void checkAllPathContainsPrimitiveCollection() throws ODataJPAModelException {
final IntermediateStructuredType<Collection> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Collection.class), schema);
final List<JPAPath> act = et.getPathList();
assertEquals(13, act.size());
assertNotNull(et.getPath("Complex/Comment"));
assertTrue(et.getPath("Complex/Comment").getLeaf().isCollection());
final IntermediateCollectionProperty<?> actIntermediate = (IntermediateCollectionProperty<?>) et.getPath(
| 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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateWrongAnnotationTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateWrongAnnotationTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.COMPLEX_PROPERTY_MISSING_PROTECTION_PATH;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.COMPLEX_PROPERTY_WRONG_PROTECTION_PATH;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_KEY_PART_OF_GROUP;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_MANDATORY_PART_OF_GROUP;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_NAVIGATION_PART_OF_GROUP;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_PROTECTED_COLLECTION;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_PROTECTED_NAVIGATION;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.PROPERTY_REQUIRED_UNKNOWN;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.PluralAttribute;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.errormodel.CollectionAttributeProtected;
import com.sap.olingo.jpa.processor.core.errormodel.ComplexProtectedNoPath;
import com.sap.olingo.jpa.processor.core.errormodel.ComplexProtectedWrongPath;
import com.sap.olingo.jpa.processor.core.errormodel.EmbeddedKeyPartOfGroup;
import com.sap.olingo.jpa.processor.core.errormodel.KeyPartOfGroup;
import com.sap.olingo.jpa.processor.core.errormodel.MandatoryPartOfGroup;
import com.sap.olingo.jpa.processor.core.errormodel.NavigationAttributeProtected;
import com.sap.olingo.jpa.processor.core.errormodel.NavigationPropertyPartOfGroup;
import com.sap.olingo.jpa.processor.core.errormodel.PersonDeepCollectionProtected;
import com.sap.olingo.jpa.processor.core.errormodel.TeamWithTransientError;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
class IntermediateWrongAnnotationTest {
private TestHelper helper;
protected static final String PUNIT_NAME = "error";
protected static EntityManagerFactory emf;
protected IntermediateAnnotationInformation annotationInfo;
@BeforeEach
void setup() throws ODataJPAModelException {
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, DataSourceHelper.createDataSource(
DataSourceHelper.DB_HSQLDB));
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
}
@Test
void checkErrorOnProtectedCollectionAttribute() {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
CollectionAttributeProtected.class), "inhouseAddress");
final IntermediateStructuredType<?> entityType = helper.schema.getEntityType(
CollectionAttributeProtected.class);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateCollectionProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema, entityType));
assertEquals(NOT_SUPPORTED_PROTECTED_COLLECTION.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnProtectedCollectionAttributeDeep() {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
PersonDeepCollectionProtected.class), "inhouseAddress");
final IntermediateStructuredType<?> entityType = helper.schema.getEntityType(PersonDeepCollectionProtected.class);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateCollectionProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema, entityType));
assertEquals(NOT_SUPPORTED_PROTECTED_COLLECTION.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnProtectedNavigationAttribute() {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
NavigationAttributeProtected.class), "teams");
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateNavigationProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper.schema.getEntityType(NavigationAttributeProtected.class), jpaAttribute, helper.schema));
assertEquals(NOT_SUPPORTED_PROTECTED_NAVIGATION.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnProtectedComplexAttributeMissingPath() {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
ComplexProtectedNoPath.class),
"administrativeInformation");
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema));
assertEquals(COMPLEX_PROPERTY_MISSING_PROTECTION_PATH.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnProtectedComplexAttributeWrongPath() throws ODataJPAModelException {
// ComplexProtectedWrongPath
final EntityType<ComplexProtectedWrongPath> jpaEt = helper.getEntityType(ComplexProtectedWrongPath.class);
final IntermediateEntityType<ComplexProtectedWrongPath> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaEt, helper.schema);
et.getEdmItem();
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
et::getProtections);
assertEquals(COMPLEX_PROPERTY_WRONG_PROTECTION_PATH.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnNavigationPropertyPartOfGroup() {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
NavigationPropertyPartOfGroup.class), "teams");
final IntermediateStructuredType<?> entityType = helper.schema.getEntityType(NavigationPropertyPartOfGroup.class);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateNavigationProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), entityType, jpaAttribute,
helper.schema));
assertEquals(NOT_SUPPORTED_NAVIGATION_PART_OF_GROUP.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnMandatoryPropertyPartOfGroup() {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
MandatoryPartOfGroup.class), "eTag");
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema));
assertEquals(NOT_SUPPORTED_MANDATORY_PART_OF_GROUP.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnKeyPropertyPartOfGroup() {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
KeyPartOfGroup.class), "iD");
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema));
assertEquals(NOT_SUPPORTED_KEY_PART_OF_GROUP.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnEmbeddedKeyPropertyPartOfGroup() {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(
EmbeddedKeyPartOfGroup.class), "key");
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema));
assertEquals(NOT_SUPPORTED_KEY_PART_OF_GROUP.name(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkErrorOnTransientFieldWithUnknownRequired() {
final EntityType<TeamWithTransientError> jpaEt = helper.getEntityType(TeamWithTransientError.class);
final IntermediateEntityType<TeamWithTransientError> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), jpaEt, helper.schema);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> et.getEdmItem());
assertEquals(PROPERTY_REQUIRED_UNKNOWN.name(), act.getId());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateOperationResultParameterTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateOperationResultParameterTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.apache.olingo.commons.api.edm.geo.SRID;
import org.apache.olingo.commons.api.edm.provider.CsdlReturnType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction.ReturnType;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmGeospatial;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperation;
class IntermediateOperationResultParameterTest {
private static final String WGS84 = "4326";
private static final String NAMESPACE = "Test";
private static final String FUNCTION_NAME = "Function";
private static final int MAX_LENGTH = 10;
private static final int PRECISION = 3;
private static final int SCALE = 15;
private IntermediateOperationResultParameter cut;
private JPAOperation jpaOperation;
private ReturnType jpaReturnType;
private EdmGeospatial geospatial;
private CsdlReturnType csdlReturnType;
@SuppressWarnings({ "unchecked", "rawtypes" })
@BeforeEach
void setup() {
jpaOperation = mock(JPAOperation.class);
jpaReturnType = mock(ReturnType.class);
csdlReturnType = mock(CsdlReturnType.class);
geospatial = mock(EdmGeospatial.class);
when(jpaOperation.getReturnType()).thenReturn(csdlReturnType);
when(jpaReturnType.maxLength()).thenReturn(MAX_LENGTH);
when(jpaReturnType.precision()).thenReturn(PRECISION);
when(jpaReturnType.scale()).thenReturn(SCALE);
when(jpaReturnType.isCollection()).thenReturn(Boolean.TRUE);
when(jpaReturnType.srid()).thenReturn(geospatial);
when(jpaReturnType.type()).thenReturn((Class) Integer.class);
when(csdlReturnType.getTypeFQN()).thenReturn(new FullQualifiedName(NAMESPACE, FUNCTION_NAME));
cut = new IntermediateOperationResultParameter(jpaOperation, jpaReturnType, Integer.class);
}
@Test
void checkTypeIsReturned() {
assertEquals(Integer.class, cut.getType());
}
@Test
void checkMaxLength() {
assertEquals(MAX_LENGTH, cut.getMaxLength());
}
@Test
void checkPrecision() {
assertEquals(PRECISION, cut.getPrecision());
}
@Test
void checkScale() {
assertEquals(SCALE, cut.getScale());
}
@Test
void checkIsCollection() {
assertEquals(Boolean.TRUE, cut.isCollection());
}
@Test
void checkFullQualifiedName() {
final FullQualifiedName act = cut.getTypeFQN();
assertEquals(FUNCTION_NAME, act.getName());
assertEquals(NAMESPACE, act.getNamespace());
}
@Test
void checkSrid() {
when(geospatial.srid()).thenReturn(WGS84);
when(geospatial.dimension()).thenReturn(Dimension.GEOMETRY);
final SRID act = cut.getSrid();
final SRID exp = SRID.valueOf(WGS84);
exp.setDimension(Dimension.GEOMETRY);
assertEquals(exp, act);
}
@Test
void checkSridNullIfNotProvided() {
when(geospatial.srid()).thenReturn("");
assertNull(cut.getSrid());
}
@Test
void checkConstructorForJavaFunctionCollection() {
cut = new IntermediateOperationResultParameter(jpaOperation, jpaReturnType, Collections.class, true);
assertEquals(Integer.class, cut.getType());
}
@Test
void checkConstructorForJavaFunctionSingle() {
cut = new IntermediateOperationResultParameter(jpaOperation, jpaReturnType, String.class, false);
assertEquals(String.class, cut.getType());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateComplexTypeTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateComplexTypeTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.processor.core.util.Assertions.assertListEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import jakarta.persistence.metamodel.EmbeddableType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
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.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ComplexSubTypeError;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ComplexSubTypeOfIgnore;
import com.sap.olingo.jpa.processor.core.testmodel.CollectionFirstLevelComplex;
import com.sap.olingo.jpa.processor.core.testmodel.ComplexBaseType;
import com.sap.olingo.jpa.processor.core.testmodel.ComplexSubType;
import com.sap.olingo.jpa.processor.core.testmodel.ComplexWithTransientComplexCollection;
import com.sap.olingo.jpa.processor.core.testmodel.InhouseAddress;
import com.sap.olingo.jpa.processor.core.testmodel.JoinComplex;
import com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData;
import com.sap.olingo.jpa.processor.core.testmodel.RestrictedEntityComplex;
class IntermediateComplexTypeTest extends TestMappingRoot {
private Set<EmbeddableType<?>> etList;
private IntermediateSchema schema;
private IntermediateAnnotationInformation annotationInfo;
@BeforeEach
void setup() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
etList = emf.getMetamodel().getEmbeddables();
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
schema = new IntermediateSchema(nameBuilder, emf.getMetamodel(), mock(
Reflections.class), annotationInfo);
}
@Test
void checkComplexTypeCanBeCreated() {
assertNotNull(new IntermediateComplexType<>(nameBuilder, getEmbeddableType("CommunicationData"),
schema));
}
private <T> EmbeddableType<T> getEmbeddableType(final Class<T> type) {
return getEmbeddableType(type.getSimpleName());
}
@SuppressWarnings("unchecked")
private <T> EmbeddableType<T> getEmbeddableType(final String typeName) {
for (final EmbeddableType<?> embeddableType : etList) {
if (embeddableType.getJavaType().getSimpleName().equals(typeName)) {
return (EmbeddableType<T>) embeddableType;
}
}
return null;
}
@Test
void checkGetAllProperties() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
getEmbeddableType("CommunicationData"), schema);
assertEquals(4, ct.getEdmItem().getProperties().size(), "Wrong number of entities");
}
@Test
void checkGetPropertyByNameNotNull() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
getEmbeddableType("CommunicationData"), schema);
assertNotNull(ct.getEdmItem().getProperty("LandlinePhoneNumber"));
}
@Test
void checkGetPropertyByNameCorrectEntity() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
getEmbeddableType("CommunicationData"), schema);
assertEquals("LandlinePhoneNumber", ct.getEdmItem().getProperty("LandlinePhoneNumber").getName());
}
@Test
void checkGetPropertyIsNullable() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType(PostalAddressData.class), schema);
// In case nullable = true, nullable is not past to $metadata, as this is the default
assertTrue(ct.getEdmItem().getProperty("POBox").isNullable());
}
@Test
void checkGetAllNavigationProperties() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType(PostalAddressData.class), schema);
assertEquals(1, ct.getEdmItem().getNavigationProperties().size(), "Wrong number of entities");
}
@Test
void checkGetNavigationPropertyByNameNotNull() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType(PostalAddressData.class), schema);
assertNotNull(ct.getEdmItem().getNavigationProperty("AdministrativeDivision").getName());
}
@Test
void checkGetNavigationPropertyByNameRightEntity() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("PostalAddressData"), schema);
assertEquals("AdministrativeDivision", ct.getEdmItem().getNavigationProperty("AdministrativeDivision").getName());
}
@Test
void checkGetPropertiesSkipIgnored() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("CommunicationData"), schema);
assertEquals(3, ct.getEdmItem().getProperties().size(), "Wrong number of entities");
}
@Test
void checkGetDescriptionPropertyManyToOne() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("PostalAddressData"), schema);
assertNotNull(ct.getEdmItem().getProperty("CountryName"));
assertTrue(ct.getAttribute("countryName").isPresent());
assertNotNull(((IntermediateDescriptionProperty) ct.getAttribute("countryName").get()).getTargetEntity());
}
@Test
void checkGetDescriptionPropertyManyToMany() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("PostalAddressData"), schema);
assertNotNull(ct.getEdmItem().getProperty("RegionName"));
}
@Test
void checkDescriptionPropertyType() throws ODataJPAModelException {
final PostProcessorSetIgnore postProcessorDouble = new PostProcessorSetIgnore();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("PostalAddressData"), schema);
ct.getEdmItem();
assertTrue(ct.getProperty("countryName") instanceof IntermediateDescriptionProperty);
}
@Test
void checkGetPropertyOfNestedComplexType() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("AdministrativeInformation"), schema);
assertNotNull(ct.getPath("Created/By"));
}
@Test
void checkGetPropertyDBName() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("PostalAddressData"), schema);
assertEquals("\"Address.PostOfficeBox\"", ct.getPath("POBox").getDBFieldName());
}
@Test
void checkGetPropertyDBNameOfNestedComplexType() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("AdministrativeInformation"), schema);
assertEquals("\"CreatedBy\"", ct.getPath("Created/By").getDBFieldName());
}
@Test
void checkGetPropertyWithComplexType() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("AdministrativeInformation"), schema);
assertNotNull(ct.getEdmItem().getProperty("Created"));
}
@Test
void checkGetPropertiesWithSameComplexTypeNotEqual() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("AdministrativeInformation"), schema);
assertNotEquals(ct.getEdmItem().getProperty("Created"), ct.getEdmItem().getProperty("Updated"));
assertNotEquals(ct.getProperty("created"), ct.getProperty("updated"));
}
@Disabled("Enumeration Type Property")
@Test
void checkGetPropertyWithEnumerationType() {
fail();
}
@Test
void checkGetPropertyIgnoreTrue() {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("DummyEmbeddedToIgnore"), schema);
assertTrue(ct.ignore());
}
@Test
void checkGetPropertyIgnoreFalse() {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("ChangeInformation"), schema);
assertFalse(ct.ignore());
}
@Test
void checkOneSimpleProtectedProperty() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("InhouseAddressWithProtection"), schema);
final List<JPAProtectionInfo> act = ct.getProtections();
assertNotNull(act);
assertEquals(1, act.size());
assertEquals("Building", act.get(0).getAttribute().getExternalName());
assertEquals("BuildingNumber", act.get(0).getClaimName());
}
@Test
void checkOneComplexProtectedPropertyDeep() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEmbeddableType("AddressDeepProtected"), schema);
final List<JPAProtectionInfo> act = ct.getProtections();
assertNotNull(act);
assertEquals(1, act.size());
assertEquals("Building", act.get(0).getAttribute().getExternalName());
assertEquals("BuildingNumber", act.get(0).getClaimName());
assertEquals(2, act.get(0).getPath().getPath().size());
assertEquals(true, act.get(0).supportsWildcards());
}
@ParameterizedTest
@CsvSource({
"Building, BuildingNumber",
"Floor, Floor",
"RoomNumber, RoomNumber"
})
void checkOneComplexProtectedPropertyDeepWoWildcards(final String externalName, final String claim)
throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType("AddressDeepThreeProtections"), schema);
final List<JPAProtectionInfo> act = ct.getProtections();
assertNotNull(act);
assertEquals(3, act.size());
JPAProtectionInfo targetAttribute = null;
for (final JPAProtectionInfo a : act) {
if (a.getAttribute().getExternalName().equals(externalName)) {
targetAttribute = a;
}
}
assertNotNull(targetAttribute);
assertEquals(claim, targetAttribute.getClaimName());
assertEquals(2, act.get(0).getPath().getPath().size());
assertFalse(act.get(0).supportsWildcards());
}
@Test
void checkTransientCollectionProperty() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(nameBuilder,
getEmbeddableType(CollectionFirstLevelComplex.class), schema);
assertTrue(ct.getAttribute("transientCollection").get().isTransient());
assertTrue(ct.getAttributes().contains(ct.getAttribute("transientCollection").get()));
assertNotNull(ct.getAssociationPathList());
}
@Test
void checkGetBaseType() throws ODataJPAModelException {
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(nameBuilder,
getEmbeddableType(ComplexSubType.class), schema);
assertNotNull(ct.getBaseType());
assertEquals(ComplexBaseType.class.getName(), ct.getBaseType().getInternalName());
}
@Test
void checkGetBaseTypeNotFound() throws ODataJPAModelException {
@SuppressWarnings("unchecked")
final EmbeddableType<ComplexSubTypeError> complexType = mock(EmbeddableType.class);
when(complexType.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ComplexSubTypeError.class;
}
});
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(nameBuilder,
complexType, schema);
assertNull(ct.getBaseType());
}
@Test
void checkGetBaseTypeBaseTypeIgnore() throws ODataJPAModelException {
@SuppressWarnings("unchecked")
final EmbeddableType<ComplexSubTypeOfIgnore> complexType = mock(EmbeddableType.class);
when(complexType.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return ComplexSubTypeError.class;
}
});
final IntermediateStructuredType<?> ct = new IntermediateComplexType<>(nameBuilder,
complexType, schema);
assertNull(ct.getBaseType());
}
private static Stream<Arguments> complexTypeClassProvider() {
return Stream.of(
Arguments.of(RestrictedEntityComplex.class),
Arguments.of(InhouseAddress.class),
Arguments.of(ComplexWithTransientComplexCollection.class),
Arguments.of(JoinComplex.class));
}
@ParameterizedTest
@MethodSource("complexTypeClassProvider")
<T> void checkAsUserGroupRestrictedCopiesUnrestrictedValues(Class<T> clazz) throws ODataJPAModelException {
final IntermediateStructuredType<T> ct = new IntermediateComplexType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEmbeddableType(clazz), schema);
final IntermediateStructuredType<T> act = ct.asUserGroupRestricted(List.of("Company"));
assertEquals(ct.getExternalFQN(), act.getExternalFQN());
assertListEquals(ct.getAttributes(), act.getAttributes(), JPAAttribute.class);
assertListEquals(ct.getDeclaredAttributes(), act.getDeclaredAttributes(), JPAAttribute.class);
assertListEquals(ct.getCollectionAttributesPath(), act.getCollectionAttributesPath(), JPAPath.class);
assertListEquals(ct.getDeclaredCollectionAttributes(), act.getDeclaredCollectionAttributes(),
JPACollectionAttribute.class);
assertListEquals(ct.getProtections(), act.getProtections(), JPAProtectionInfo.class);
assertEquals(ct.isAbstract(), act.isAbstract());
assertEquals(ct.ignore(), act.ignore());
}
@Test
void checkAsUserGroupRestrictedUserOwnBaseType() throws ODataJPAModelException {
final IntermediateStructuredType<ComplexSubType> ct = new IntermediateComplexType<>(nameBuilder,
getEmbeddableType(ComplexSubType.class), schema);
final IntermediateStructuredType<ComplexSubType> act = ct.asUserGroupRestricted(List.of("Company"));
assertNotEquals(ct.getBaseType(), act.getBaseType());
}
//
// @Test
// void checkAsUserGroupRestrictedUserRestrictsNavigations() throws ODataJPAModelException {
// final IntermediateEntityType<Person> et = new IntermediateEntityType<>(
// new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(Person.class), schema);
//
// final IntermediateEntityType<Person> act = et.asUserGroupRestricted(List.of("Company"));
// assertListEquals(et.getDeclaredAssociations(), act.getDeclaredAssociations(), JPAAssociationAttribute.class);
// assertListEquals(et.getAssociationPathList(), act.getAssociationPathList(), JPAAssociationPath.class);
// assertListEquals(et.getEdmItem().getNavigationProperties(), act.getEdmItem().getNavigationProperties(),
// CsdlNavigationProperty.class);
// final IntermediateEntityType<Person> act2 = et.asUserGroupRestricted(List.of("Person"));
// assertEquals(et.getDeclaredAssociations().size() - 1, act2.getDeclaredAssociations().size());
// assertEquals(et.getAssociationPathList().size() - 1, act2.getAssociationPathList().size());
// assertEquals(et.getEdmItem().getNavigationProperties().size() - 1, act2.getEdmItem().getNavigationProperties()
// .size());
// }
private static class PostProcessorSetIgnore implements JPAEdmMetadataPostProcessor {
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
if (jpaManagedTypeClassName.equals(COMM_CANONICAL_NAME)
&& property.getInternalName().equals("landlinePhoneNumber")) {
property.setIgnore(true);
}
}
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {
if (jpaManagedTypeClassName.equals(ADDR_CANONICAL_NAME)
&& property.getInternalName().equals("countryName")) {
property.setIgnore(false);
}
}
@Override
public void provideReferences(final IntermediateReferenceList references) {
// Not needed
}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {
// Not needed
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPATypeConverterTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPATypeConverterTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.SimpleTimeZone;
import java.util.UUID;
import java.util.stream.Stream;
import jakarta.persistence.Lob;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.persistence.metamodel.Attribute;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmGeospatial;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class JPATypeConverterTest {
static Stream<Arguments> mappingJavaLobToOData() {
return Stream.of(
arguments(Blob.class, buildLobAttribute(), EdmPrimitiveTypeKind.Binary),
arguments(Clob.class, buildLobAttribute(), EdmPrimitiveTypeKind.String));
}
static Stream<Arguments> mappingJavaTimeToOData() {
return Stream.of(
arguments(java.time.LocalTime.class, null, EdmPrimitiveTypeKind.TimeOfDay),
arguments(java.sql.Time.class, null, EdmPrimitiveTypeKind.TimeOfDay),
arguments(java.time.Duration.class, null, EdmPrimitiveTypeKind.Duration),
arguments(java.time.LocalDate.class, null, EdmPrimitiveTypeKind.Date),
arguments(java.sql.Date.class, null, EdmPrimitiveTypeKind.Date),
arguments(Calendar.class, null, EdmPrimitiveTypeKind.DateTimeOffset),
arguments(Calendar.class, buildTimeAttribute(TemporalType.TIME), EdmPrimitiveTypeKind.TimeOfDay),
arguments(Calendar.class, buildTimeAttribute(TemporalType.DATE), EdmPrimitiveTypeKind.Date),
arguments(Calendar.class, buildTimeAttribute(TemporalType.TIMESTAMP), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(Calendar.class, buildTimeAttribute(null), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(Timestamp.class, null, EdmPrimitiveTypeKind.DateTimeOffset),
arguments(Timestamp.class, buildTimeAttribute(TemporalType.TIME), EdmPrimitiveTypeKind.TimeOfDay),
arguments(Timestamp.class, buildTimeAttribute(TemporalType.DATE), EdmPrimitiveTypeKind.Date),
arguments(Timestamp.class, buildTimeAttribute(TemporalType.TIMESTAMP), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(Timestamp.class, buildTimeAttribute(null), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(java.util.Date.class, null, EdmPrimitiveTypeKind.DateTimeOffset),
arguments(java.util.Date.class, buildTimeAttribute(TemporalType.TIME), EdmPrimitiveTypeKind.TimeOfDay),
arguments(java.util.Date.class, buildTimeAttribute(TemporalType.DATE), EdmPrimitiveTypeKind.Date),
arguments(java.util.Date.class, buildTimeAttribute(TemporalType.TIMESTAMP),
EdmPrimitiveTypeKind.DateTimeOffset),
arguments(java.time.OffsetDateTime.class, buildTimeAttribute(null), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(java.time.LocalDateTime.class, buildTimeAttribute(null), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(java.time.ZonedDateTime.class, buildTimeAttribute(null), EdmPrimitiveTypeKind.DateTimeOffset),
arguments(java.time.Instant.class, buildTimeAttribute(null), EdmPrimitiveTypeKind.DateTimeOffset));
}
static Stream<Arguments> mappingSimpleJavaToOData() {
return Stream.of(
arguments(Long.class, EdmPrimitiveTypeKind.Int64),
arguments(long.class, EdmPrimitiveTypeKind.Int64),
arguments(Integer.class, EdmPrimitiveTypeKind.Int32),
arguments(int.class, EdmPrimitiveTypeKind.Int32),
arguments(Short.class, EdmPrimitiveTypeKind.Int16),
arguments(short.class, EdmPrimitiveTypeKind.Int16),
arguments(String.class, EdmPrimitiveTypeKind.String),
arguments(Character.class, EdmPrimitiveTypeKind.String),
arguments(char.class, EdmPrimitiveTypeKind.String),
arguments(char[].class, EdmPrimitiveTypeKind.String),
arguments(Character[].class, EdmPrimitiveTypeKind.String),
arguments(Double.class, EdmPrimitiveTypeKind.Double),
arguments(double.class, EdmPrimitiveTypeKind.Double),
arguments(Float.class, EdmPrimitiveTypeKind.Single),
arguments(float.class, EdmPrimitiveTypeKind.Single),
arguments(BigDecimal.class, EdmPrimitiveTypeKind.Decimal),
arguments(Byte.class, EdmPrimitiveTypeKind.SByte),
arguments(byte.class, EdmPrimitiveTypeKind.SByte),
arguments(byte[].class, EdmPrimitiveTypeKind.Binary),
arguments(Boolean.class, EdmPrimitiveTypeKind.Boolean),
arguments(boolean.class, EdmPrimitiveTypeKind.Boolean),
arguments(UUID.class, EdmPrimitiveTypeKind.Guid));
}
static Stream<Arguments> mappingJavaGeographyToOData() {
return Stream.of(
arguments(org.apache.olingo.commons.api.edm.geo.Point.class, buildDimensionAttribute(Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyPoint),
arguments(org.apache.olingo.commons.api.edm.geo.MultiPoint.class, buildDimensionAttribute(Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyMultiPoint),
arguments(org.apache.olingo.commons.api.edm.geo.LineString.class, buildDimensionAttribute(Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyLineString),
arguments(org.apache.olingo.commons.api.edm.geo.MultiLineString.class, buildDimensionAttribute(
Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyMultiLineString),
arguments(org.apache.olingo.commons.api.edm.geo.Polygon.class, buildDimensionAttribute(Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyPolygon),
arguments(org.apache.olingo.commons.api.edm.geo.MultiPolygon.class, buildDimensionAttribute(
Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyMultiPolygon),
arguments(org.apache.olingo.commons.api.edm.geo.GeospatialCollection.class, buildDimensionAttribute(
Dimension.GEOGRAPHY),
EdmPrimitiveTypeKind.GeographyCollection)
);
}
static Stream<Arguments> mappingJavaGeometryToOData() {
return Stream.of(
arguments(org.apache.olingo.commons.api.edm.geo.Point.class, buildDimensionAttribute(Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryPoint),
arguments(org.apache.olingo.commons.api.edm.geo.MultiPoint.class, buildDimensionAttribute(Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryMultiPoint),
arguments(org.apache.olingo.commons.api.edm.geo.LineString.class, buildDimensionAttribute(Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryLineString),
arguments(org.apache.olingo.commons.api.edm.geo.MultiLineString.class, buildDimensionAttribute(
Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryMultiLineString),
arguments(org.apache.olingo.commons.api.edm.geo.Polygon.class, buildDimensionAttribute(Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryPolygon),
arguments(org.apache.olingo.commons.api.edm.geo.MultiPolygon.class, buildDimensionAttribute(
Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryMultiPolygon),
arguments(org.apache.olingo.commons.api.edm.geo.GeospatialCollection.class, buildDimensionAttribute(
Dimension.GEOMETRY),
EdmPrimitiveTypeKind.GeometryCollection)
);
}
static Stream<Arguments> scalarJavaTypes() {
return Stream.of(
arguments(Integer.class, null, true),
arguments(String.class, null, true),
arguments(Character.class, null, true),
arguments(Long.class, null, true),
arguments(Short.class, null, true),
arguments(Integer.class, null, true),
arguments(Double.class, null, true),
arguments(Float.class, null, true),
arguments(BigDecimal.class, null, true),
arguments(Byte.class, null, true),
arguments(Boolean.class, null, true),
arguments(java.time.LocalTime.class, null, true),
arguments(java.sql.Time.class, null, true),
arguments(java.time.Duration.class, null, true),
arguments(java.time.LocalDate.class, null, true),
arguments(java.time.Instant.class, null, true),
arguments(java.sql.Date.class, null, true),
arguments(Calendar.class, null, true),
arguments(Timestamp.class, null, true),
arguments(java.util.Date.class, null, true),
arguments(UUID.class, null, true),
arguments(Attribute.class, null, false));
}
static Stream<Arguments> supportedByOlingo() {
return Stream.of(
arguments(Boolean.class, true),
arguments(Byte.class, true),
arguments(Byte[].class, true),
arguments(byte[].class, true),
arguments(Double.class, true),
arguments(Float.class, true),
arguments(Integer.class, true),
arguments(java.math.BigDecimal.class, true),
arguments(java.math.BigInteger.class, true),
arguments(java.sql.Time.class, true),
arguments(java.sql.Timestamp.class, true),
arguments(java.util.Calendar.class, true),
arguments(java.util.Date.class, true),
arguments(java.util.UUID.class, true),
arguments(Long.class, true),
arguments(Short.class, true),
arguments(String.class, true),
arguments(LocalDate.class, true),
arguments(LocalTime.class, true),
arguments(ZonedDateTime.class, true),
arguments(LocalDateTime.class, false),
arguments(OffsetDateTime.class, false),
arguments(Instant.class, true));
}
static Stream<Arguments> simpleJavaTypes() {
return Stream.concat(scalarJavaTypes(), Stream.of(
arguments(Integer.class, null, true)));
}
private static Attribute<?, ?> buildLobAttribute() {
final Attribute<?, ?> a = mock(Attribute.class);
final AnnotatedElement e = mock(AnnotatedElement.class, Mockito.withSettings().extraInterfaces(Member.class));
final Lob l = mock(Lob.class);
when(a.getJavaMember()).thenReturn((Member) e);
when(e.getAnnotation(Lob.class)).thenReturn(l);
when(a.getName()).thenReturn("Lob");
return a;
}
private static Attribute<?, ?> buildTimeAttribute(final TemporalType time) {
final Attribute<?, ?> a = mock(Attribute.class);
final AnnotatedElement e = mock(AnnotatedElement.class, Mockito.withSettings().extraInterfaces(Member.class));
final Temporal t = mock(Temporal.class);
when(a.getJavaMember()).thenReturn((Member) e);
when(e.getAnnotation(Temporal.class)).thenReturn(t);
when(t.value()).thenReturn(time);
return a;
}
private static Attribute<?, ?> buildDimensionAttribute(final Dimension dimension) {
final Attribute<?, ?> a = mock(Attribute.class);
final AnnotatedElement e = mock(AnnotatedElement.class, Mockito.withSettings().extraInterfaces(Member.class));
final EdmGeospatial g = mock(EdmGeospatial.class);
when(a.getJavaMember()).thenReturn((Member) e);
when(e.getAnnotation(EdmGeospatial.class)).thenReturn(g);
when(g.dimension()).thenReturn(dimension);
return a;
}
@ParameterizedTest
@MethodSource({ "mappingJavaGeographyToOData", "mappingJavaGeometryToOData" })
void checkConvertJavaGeographyToOData(final Class<?> javaType, final Attribute<?, ?> jpaAttribute,
final EdmPrimitiveTypeKind odataType) throws ODataJPAModelException {
assertEquals(odataType, JPATypeConverter.convertToEdmSimpleType(javaType, jpaAttribute));
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> JPATypeConverter.convertToEdmSimpleType(javaType, buildTimeAttribute(TemporalType.TIME)));
assertEquals(ODataJPAModelException.MessageKeys.TYPE_NOT_SUPPORTED.getKey(), act.getId());
}
@ParameterizedTest
@MethodSource("mappingJavaTimeToOData")
void checkConvertJavaDateTimeToOData(final Class<?> javaType, final Attribute<?, ?> jpaAttribute,
final EdmPrimitiveTypeKind odataType) throws ODataJPAModelException {
assertEquals(odataType, JPATypeConverter.convertToEdmSimpleType(javaType, jpaAttribute));
}
@ParameterizedTest
@MethodSource("mappingSimpleJavaToOData")
void checkConvertSimpleJavaToOData(final Class<?> javaType, final EdmPrimitiveTypeKind odataType)
throws ODataJPAModelException {
assertEquals(odataType, JPATypeConverter.convertToEdmSimpleType(javaType));
}
@ParameterizedTest
@MethodSource("scalarJavaTypes")
void checkIsScalarJavaType(final Class<?> javaType, final Attribute<?, ?> jpaAttribute,
final boolean isScalar) {
assertEquals(isScalar, JPATypeConverter.isScalarType(javaType));
}
@ParameterizedTest
@MethodSource("simpleJavaTypes")
void checkIsSimpleJavaType(final Class<?> javaType, final Attribute<?, ?> jpaAttribute,
final boolean isSimple) {
assertEquals(isSimple, JPATypeConverter.isSimpleType(javaType, jpaAttribute));
}
@ParameterizedTest
@MethodSource("supportedByOlingo")
void checkIsSupportedByOlingo(final Class<?> javaType, final boolean isSupported) {
assertEquals(isSupported, JPATypeConverter.isSupportedByOlingo(javaType));
}
@Test
void checkReturnsNullOnUnknownTypeWithoutAnnotation() throws ODataJPAModelException {
assertNull(JPATypeConverter.convertToEdmSimpleType(SimpleTimeZone.class));
}
@Test
void checkThrowsExceptionOnUnknownTypeWithAnnotation() {
assertThrows(ODataJPAModelException.class,
() -> JPATypeConverter.convertToEdmSimpleType(SimpleTimeZone.class, buildTimeAttribute(TemporalType.TIME)));
}
@Test
void checkThrowsExceptionOnUnknownGeographyType() {
assertThrows(ODataJPAModelException.class,
() -> JPATypeConverter.convertToEdmSimpleType(SimpleTimeZone.class, buildDimensionAttribute(
Dimension.GEOGRAPHY)));
}
@Test
void checkThrowsExceptionOnUnknownGeometryType() {
assertThrows(ODataJPAModelException.class,
() -> JPATypeConverter.convertToEdmSimpleType(SimpleTimeZone.class, buildDimensionAttribute(
Dimension.GEOMETRY)));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateJoinTableTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateJoinTableTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.JoinTable;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EntityType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
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.testmodel.JoinSource;
class IntermediateJoinTableTest extends TestMappingRoot {
private IntermediateSchema schema;
private TestHelper helper;
private JoinTable jpaJoinTable;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateNavigationProperty<?> property;
private IntermediateJoinTable cut;
@BeforeEach
void setup() throws ODataJPAModelException, NoSuchFieldException, SecurityException {
final Reflections reflections = mock(Reflections.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), reflections,
annotationInfo);
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
jpaJoinTable = determineJoinTable(JoinSource.class, "oneToMany");
property = buildNavigationProperty(JoinSource.class, "oneToMany");
}
private <S> IntermediateNavigationProperty<S> buildNavigationProperty(final Class<S> clazz,
final String attribute) throws ODataJPAModelException {
final EntityType<S> et = helper.getEntityType(clazz);
final IntermediateStructuredType<S> st = schema.getEntityType(clazz);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(et, attribute);
return new IntermediateNavigationProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
st, jpaAttribute, schema);
}
private JoinTable determineJoinTable(final Class<JoinSource> clazz, final String attribute)
throws NoSuchFieldException, SecurityException {
return clazz.getDeclaredField(attribute).getAnnotation(JoinTable.class);
}
@Test
void checkCreateJoinTable() {
assertNotNull(new IntermediateJoinTable(property, jpaJoinTable, schema));
}
@Test
void checkGetLeftColumns() throws ODataJPAModelException {
property.getEdmItem();
cut = new IntermediateJoinTable(property, jpaJoinTable, schema);
final List<JPAPath> act = cut.getLeftColumnsList();
assertNotNull(act);
assertFalse(act.isEmpty());
assertEquals("\"SourceKey\"", act.get(0).getDBFieldName());
}
@Test
void checkGetRightColumns() throws ODataJPAModelException {
cut = new IntermediateJoinTable(property, jpaJoinTable, schema);
final List<JPAPath> act = cut.getRightColumnsList();
assertNotNull(act);
assertFalse(act.isEmpty());
assertEquals("\"TargetKey\"", act.get(0).getDBFieldName());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEnumerationTypeTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEnumerationTypeTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockitoAnnotations;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.DayOfWeek;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.EnumWithConverterError;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.FileAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongMember;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongType;
class IntermediateEnumerationTypeTest extends TestMappingRoot {
private IntermediateEnumerationType cut;
private IntermediateAnnotationInformation annotationInfo;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
}
@Test
void checkCsdlEnumTypeAccessible() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
assertNotNull(cut.getEdmItem());
}
@Test
void checkNameProvided() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
cut.getEdmItem();
assertEquals("DayOfWeek", cut.getEdmItem().getName());
}
@Test
void checkIsFlagProvidesFalse() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
assertFalse(cut.isFlags());
}
@Test
void checkIsFlagProvidesTrue() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
cut.getEdmItem();
assertTrue(cut.isFlags());
}
@Test
void checkIsFlagOnEdmTypeProvidesFalse() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
cut.getEdmItem();
assertFalse(cut.getEdmItem().isFlags());
}
@Test
void checkIsFlagOnEdmProvidesTrue() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
cut.getEdmItem();
assertTrue(cut.getEdmItem().isFlags());
}
@Test
void checkUnderlyingTypeIntegerAsDefault() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
cut.getEdmItem();
assertEquals(EdmPrimitiveTypeKind.Int32.getFullQualifiedName().getFullQualifiedNameAsString(), cut.getEdmItem()
.getUnderlyingType());
}
@Test
void checkUnderlyingTypeFromConverter() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
cut.getEdmItem();
assertEquals(EdmPrimitiveTypeKind.Int16.getFullQualifiedName().getFullQualifiedNameAsString(), cut.getEdmItem()
.getUnderlyingType());
}
@Test
void checkReturnsRightNumberOfMember4() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
cut.getEdmItem();
assertEquals(4, cut.getEdmItem().getMembers().size());
}
@Test
void checkReturnsRightNumberOfMember7() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
cut.getEdmItem();
assertEquals(7, cut.getEdmItem().getMembers().size());
}
@Test
void checkReturnsRightNameForMembersOfDayOfWeek() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
cut.getEdmItem();
assertEquals("MONDAY", cut.getEdmItem().getMembers().get(0).getName());
assertEquals("SUNDAY", cut.getEdmItem().getMembers().get(6).getName());
}
@Test
void checkReturnsRightValueForMembersOfDayOfWeek() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
cut.getEdmItem();
assertEquals("0", cut.getEdmItem().getMembers().get(0).getValue());
assertEquals("6", cut.getEdmItem().getMembers().get(6).getValue());
}
@Test
void checkReturnsRightNameForMembersOfFileAccess() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
cut.getEdmItem();
assertEquals("Read", cut.getEdmItem().getMembers().get(0).getName());
assertEquals("Delete", cut.getEdmItem().getMembers().get(3).getName());
}
@Test
void checkReturnsRightValueForMembersOfFileAccess() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
cut.getEdmItem();
assertEquals("1", cut.getEdmItem().getMembers().get(0).getValue());
assertEquals("8", cut.getEdmItem().getMembers().get(3).getValue());
}
@Test
void checkThrowsErrorOnIsFlagTrueAndNegativeValue() {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), WrongMember.class, annotationInfo);
assertThrows(ODataJPAModelException.class, () -> {
cut.getEdmItem();
});
}
@Test
void checkThrowsErrorOnNotSupportedUnderlyingType() {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), WrongType.class, annotationInfo);
assertThrows(ODataJPAModelException.class, () -> {
cut.getEdmItem();
});
}
@Test
void checkOrdinalMemberProvidedFromStringWOConverter() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
assertEquals(DayOfWeek.SUNDAY, cut.enumOf("SUNDAY"));
}
@Test
void checkOrdinalMemberProvidedFromNumberWOConverter() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), DayOfWeek.class, annotationInfo);
assertEquals(DayOfWeek.TUESDAY, cut.enumOf(1));
}
@Test
void checkOrdinalMemberProvidedFromStringWithConverter() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
assertEquals(FileAccess.Create, cut.enumOf("Create"));
}
@Test
void checkOrdinalMemberProvidedFromNumberWithConverter() throws ODataJPAModelException {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), FileAccess.class, annotationInfo);
assertEquals(FileAccess.Write, cut.enumOf((short) 2));
}
@Test
void checkValueOfRethrowsConstructorException() {
cut = new IntermediateEnumerationType(new JPADefaultEdmNameBuilder(PUNIT_NAME), EnumWithConverterError.class,
annotationInfo);
assertThrows(ODataJPAModelException.class, () -> cut.lazyBuildEdmItem());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestHelper.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestHelper.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.ManagedType;
import jakarta.persistence.metamodel.Metamodel;
import jakarta.persistence.metamodel.PluralAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctions;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.AccessRights;
import com.sap.olingo.jpa.processor.core.testmodel.UserType;
public class TestHelper {
private final Metamodel jpaMetamodel;
public final IntermediateSchema schema;
final IntermediateAnnotationInformation annotationInfo;
public TestHelper(final Metamodel metamodel, final String namespace) throws ODataJPAModelException {
this(metamodel, namespace, new ArrayList<>());
}
public TestHelper(final Metamodel metamodel, final String namespace,
final List<AnnotationProvider> annotationProviderList) throws ODataJPAModelException {
final Reflections reflections = mock(Reflections.class);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class, AccessRights.class, UserType.class)));
annotationInfo = new IntermediateAnnotationInformation(annotationProviderList, mock(IntermediateReferences.class));
this.jpaMetamodel = metamodel;
this.schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(namespace), jpaMetamodel, reflections,
annotationInfo);
}
public Object findAttribute(final List<? extends JPAAttribute> attributes, final String searchItem) {
for (final JPAAttribute attribute : attributes) {
if (attribute.getExternalName().equals(searchItem))
return attribute;
}
return null;
}
public Attribute<?, ?> getAttribute(final ManagedType<?> et, final String attributeName) {
for (final SingularAttribute<?, ?> attribute : et.getSingularAttributes()) {
if (attribute.getName().equals(attributeName))
return attribute;
}
return null;
}
public PluralAttribute<?, ?, ?> getCollectionAttribute(final ManagedType<?> et, final String attributeName) {
for (final PluralAttribute<?, ?, ?> attribute : et.getPluralAttributes()) {
if (attribute.getName().equals(attributeName))
return attribute;
}
return null;
}
@SuppressWarnings("unchecked")
public <T> EmbeddableType<T> getComplexType(final String typeName) {
for (final EmbeddableType<?> embeddableType : jpaMetamodel.getEmbeddables()) {
if (embeddableType.getJavaType().getSimpleName().equals(typeName)) {
return (EmbeddableType<T>) embeddableType;
}
}
return null;
}
public <T> EmbeddableType<T> getComplexType(final Class<T> clazz) {
try {
return jpaMetamodel.embeddable(clazz);
} catch (final IllegalArgumentException e) {
return null;
}
}
public Attribute<?, ?> getDeclaredAttribute(final ManagedType<?> et, final String attributeName) {
for (final Attribute<?, ?> attribute : et.getDeclaredAttributes()) {
if (attribute.getName().equals(attributeName))
return attribute;
}
return null;
}
public EmbeddableType<?> getEmbeddableType(final String typeName) {
for (final EmbeddableType<?> embeddableType : jpaMetamodel.getEmbeddables()) {
if (embeddableType.getJavaType().getSimpleName().equals(typeName)) {
return embeddableType;
}
}
return null;
}
public <T> EmbeddableType<T> getEmbeddableType(final Class<T> clazz) {
try {
return jpaMetamodel.embeddable(clazz);
} catch (final IllegalArgumentException e) {
return null;
}
}
public <T> EntityType<T> getEntityType(final Class<T> clazz) {
try {
return jpaMetamodel.entity(clazz);
} catch (final IllegalArgumentException e) {
return null;
}
}
public EdmFunction getStoredProcedure(final EntityType<?> jpaEntityType, final String string) {
if (jpaEntityType.getJavaType() instanceof AnnotatedElement) {
final EdmFunctions jpaStoredProcedureList = jpaEntityType.getJavaType()
.getAnnotation(EdmFunctions.class);
if (jpaStoredProcedureList != null) {
for (final EdmFunction jpaStoredProcedure : jpaStoredProcedureList.value()) {
if (jpaStoredProcedure.name().equals(string)) return jpaStoredProcedure;
}
}
}
return null;
}
} | java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateDescriptionPropertyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateDescriptionPropertyTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.util.Collections;
import java.util.List;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.ManagedType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmDescriptionAssociation;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
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.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.Country;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
class IntermediateDescriptionPropertyTest extends TestMappingRoot {
private TestHelper helper;
private IntermediateDescriptionProperty cut;
private JPAEdmMetadataPostProcessor processor;
private IntermediateStructuredType<?> et;
private JPAEdmNameBuilder nameBuilder;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
processor = mock(JPAEdmMetadataPostProcessor.class);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
final EntityType<?> type = helper.getEntityType(BusinessPartner.class);
et = new IntermediateEntityType<>(nameBuilder, type, helper.schema);
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
}
@Test
void checkPropertyCanBeCreated() throws ODataJPAModelException {
final EmbeddableType<?> type = helper.getEmbeddableType("PostalAddressData");
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(type, "countryName");
assertNotNull(new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema));
}
@Test
void checkGetDescriptionAttributeReturnsAttribute() throws ODataJPAModelException {
createDefaultCut();
assertNotNull(cut.getDescriptionAttribute());
assertEquals("name", cut.getDescriptionAttribute().getInternalName());
}
@Test
void checkGetFixedValueAssignmentReturnsEmptyList() throws ODataJPAModelException {
createDefaultCut();
assertNotNull(cut.getFixedValueAssignment());
assertTrue(cut.getFixedValueAssignment().isEmpty());
}
@Test
void checkGetFixedValueAssignmentReturnsList() throws ODataJPAModelException {
final EntityType<?> type = helper.getEntityType(Person.class);
et = new IntermediateEntityType<>(nameBuilder, type, helper.schema);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"locationName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
cut.lazyBuildEdmItem();
assertNotNull(cut.getFixedValueAssignment());
assertEquals(2, cut.getFixedValueAssignment().size());
}
@Test
void checkGetTypeReturnsDescAttributeType() throws ODataJPAModelException {
createDefaultCut();
assertNotNull(cut.getType());
assertEquals(String.class, cut.getType());
}
@Test
void checkIsAssociationReturnsTrue() throws ODataJPAModelException {
createDefaultCut();
assertTrue(cut.isAssociation());
}
@Test
void checkGetLocaleFieldNameReturnsPath() throws ODataJPAModelException {
createDefaultCut();
assertNotNull(cut.getLocaleFieldName());
assertEquals("\"LanguageISO\"", cut.getLocaleFieldName().getDBFieldName());
}
@Test
void checkGetPropertyNameOneToMany() throws ODataJPAModelException {
createDefaultCut();
assertEquals("CountryName", cut.getEdmItem().getName(), "Wrong name");
}
@Test
void checkGetPropertyNameManyToMany() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"regionName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
assertEquals("RegionName", cut.getEdmItem().getName(), "Wrong name");
}
@Test
void checkGetPropertyType() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
assertEquals(EdmPrimitiveTypeKind.String.getFullQualifiedName().getFullQualifiedNameAsString(),
cut.getEdmItem().getType(), "Wrong type");
}
@Test
void checkGetTargetEntity() throws ODataJPAModelException {
createDefaultCut();
final JPAStructuredType target = cut.getTargetEntity();
assertEquals("Country", target.getExternalName());
}
@Test
void checkGetPartnerNull() throws ODataJPAModelException {
createDefaultCut();
assertNull(cut.getPartner());
}
@Test
void checkGetPropertyIgnoreFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
final IntermediatePropertyAccess property = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et,
helper.schema);
assertFalse(property.ignore());
}
@Test
void checkGetPropertyFacetsNullableTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
assertTrue(cut.getEdmItem().isNullable());
}
@Test
void checkGetPropertyMaxLength() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
assertEquals(Integer.valueOf(100), cut.getEdmItem().getMaxLength());
}
@Test
void checkWrongPathElementThrowsException() {
final Attribute<?, ?> jpaAttribute = mock(Attribute.class);
final EdmDescriptionAssociation association = prepareCheckPath(jpaAttribute);
final EdmDescriptionAssociation.valueAssignment[] valueAssignments =
new EdmDescriptionAssociation.valueAssignment[1];
final EdmDescriptionAssociation.valueAssignment valueAssignment = mock(
EdmDescriptionAssociation.valueAssignment.class);
valueAssignments[0] = valueAssignment;
when(valueAssignment.attribute()).thenReturn("communicationData/dummy");
when(association.valueAssignments()).thenReturn(valueAssignments);
try {
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
cut.getEdmItem();
} catch (final ODataJPAModelException e) {
return;
}
fail();
}
@Test
void checkWrongPathStartThrowsException() {
final Attribute<?, ?> jpaAttribute = mock(Attribute.class);
final EdmDescriptionAssociation association = prepareCheckPath(jpaAttribute);
final EdmDescriptionAssociation.valueAssignment[] valueAssignments =
new EdmDescriptionAssociation.valueAssignment[1];
final EdmDescriptionAssociation.valueAssignment valueAssignment = mock(
EdmDescriptionAssociation.valueAssignment.class);
valueAssignments[0] = valueAssignment;
when(valueAssignment.attribute()).thenReturn("communicationDummy/dummy");
when(association.valueAssignments()).thenReturn(valueAssignments);
try {
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
cut.getEdmItem();
} catch (final ODataJPAModelException e) {
return;
}
fail();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private EdmDescriptionAssociation prepareCheckPath(final Attribute<?, ?> jpaAttribute) {
final AnnotatedMember jpaField = mock(AnnotatedMember.class);
final ManagedType jpaManagedType = mock(ManagedType.class);
final EdmDescriptionAssociation association = mock(EdmDescriptionAssociation.class);
when(jpaAttribute.getJavaType()).thenAnswer(new Answer<Class<BusinessPartner>>() {
@Override
public Class<BusinessPartner> answer(final InvocationOnMock invocation) throws Throwable {
return BusinessPartner.class;
}
});
when(jpaAttribute.getJavaMember()).thenReturn(jpaField);
when(jpaAttribute.getName()).thenReturn("dummy");
when(jpaAttribute.getDeclaringType()).thenReturn(jpaManagedType);
when(jpaManagedType.getJavaType()).thenReturn(BusinessPartner.class);
when(jpaField.getAnnotation(EdmDescriptionAssociation.class)).thenReturn(association);
when(association.descriptionAttribute()).thenReturn("country");
when(association.languageAttribute()).thenReturn("language");
when(association.localeAttribute()).thenReturn("");
return association;
}
@Test
void checkAnnotations() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class),
"locationName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
final List<CsdlAnnotation> annotations = cut.getEdmItem().getAnnotations();
assertEquals(1, annotations.size());
assertEquals("Core.IsLanguageDependent", annotations.get(0).getTerm());
assertEquals(ConstantExpressionType.Bool, annotations.get(0).getExpression().asConstant().getType());
assertEquals("true", annotations.get(0).getExpression().asConstant().getValue());
assertNull(annotations.get(0).getQualifier());
}
@Test
void checkPostProcessorCalled() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(processor);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
cut.getEdmItem();
verify(processor, atLeastOnce()).processProperty(cut, ADDR_CANONICAL_NAME);
}
@Test
void checkPostProcessorAnnotationAdded() throws ODataJPAModelException {
final PostProcessorSetName pPDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(pPDouble);
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
assertEquals(1L, cut.getEdmItem().getAnnotations().stream().filter(a -> a.getTerm().equals("Immutable")).count());
}
@Test
void checkEmptyAssociationThrowsException() throws ODataJPAModelException {
cut = new IntermediateDescriptionProperty(nameBuilder, createAttributeMock(false, false, 0), et, helper.schema);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class, () -> cut.lazyBuildEdmItem());
assertEquals(ODataJPAModelException.MessageKeys.DESCRIPTION_ANNOTATION_MISSING.getKey(), act.getId());
}
@Test
void checkUnknownAttributeAtTargetThrowsException() throws ODataJPAModelException {
cut = new IntermediateDescriptionProperty(nameBuilder, createAttributeMock(true, false, 0), et, helper.schema);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class, () -> cut.lazyBuildEdmItem());
assertEquals(ODataJPAModelException.MessageKeys.INVALID_DESCRIPTION_PROPERTY.getKey(), act.getId());
}
@Test
void checkNoLocationAtTargetThrowsException() throws ODataJPAModelException {
cut = new IntermediateDescriptionProperty(nameBuilder, createAttributeMock(true, true, 0), et, helper.schema);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class, () -> cut.lazyBuildEdmItem());
assertEquals(ODataJPAModelException.MessageKeys.DESCRIPTION_LOCALE_FIELD_MISSING.getKey(), act.getId());
}
@Test
void checkLocationAndLanguageAtTargetThrowsException() throws ODataJPAModelException {
cut = new IntermediateDescriptionProperty(nameBuilder, createAttributeMock(true, true, 2), et, helper.schema);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class, () -> cut.lazyBuildEdmItem());
assertEquals(ODataJPAModelException.MessageKeys.DESCRIPTION_LOCALE_FIELD_MISSING.getKey(), act.getId());
}
@Test
void checkGetPathReturns() throws ODataJPAModelException {
createDefaultCut();
assertNotNull(cut.getPath());
}
@Test
void checkPathLeftColumnsListEmpty() throws ODataJPAModelException {
createDefaultCut();
assertTrue(cut.getPath().getLeftColumnsList().isEmpty());
}
@Test
void checkPathRightColumnsListEmpty() throws ODataJPAModelException {
createDefaultCut();
assertTrue(cut.getPath().getRightColumnsList().isEmpty());
}
@Test
void checkGetLeafNull() throws ODataJPAModelException {
createDefaultCut();
assertNull(cut.getPath().getLeaf());
}
@Test
void checkPathGetPathEmpty() throws ODataJPAModelException {
createDefaultCut();
assertTrue(cut.getPath().getPath().isEmpty());
}
@Test
void checkPathGetInverseLeftJoinColumnsListEmpty() throws ODataJPAModelException {
createDefaultCut();
assertTrue(cut.getPath().getInverseLeftJoinColumnsList().isEmpty());
}
@Test
void checkPathIsCollectionFalse() throws ODataJPAModelException {
createDefaultCut();
assertFalse(cut.getPath().isCollection());
}
@Test
void checkPathGetPartnerNull() throws ODataJPAModelException {
createDefaultCut();
assertNull(cut.getPath().getPartner());
}
@Test
void checkPathGetJoinTableNull() throws ODataJPAModelException {
createDefaultCut();
assertNull(cut.getPath().getJoinTable());
}
@Test
void checkPathGetSource() throws ODataJPAModelException {
createDefaultCut();
final JPAStructuredType act = cut.getPath().getSourceType();
assertEquals("BusinessPartner", act.getExternalName());
}
@Test
void checkPathGetAliasNull() throws ODataJPAModelException {
createDefaultCut();
final JPAAssociationPath act = cut.getPath();
assertNull(act.getAlias());
}
@Test
void checkPathHasJoinTableNull() throws ODataJPAModelException {
createDefaultCut();
final JPAAssociationPath act = cut.getPath();
assertNull(act.getJoinTable());
}
@Test
void checkPathGetForeignKeyColumns() throws ODataJPAModelException {
createDefaultCut();
final var act = cut.getPath().getForeignKeyColumns();
assertNotNull(act);
assertTrue(act.isEmpty());
}
private static class PostProcessorSetName implements JPAEdmMetadataPostProcessor {
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
if (jpaManagedTypeClassName.equals(ADDR_CANONICAL_NAME)
&& property.getInternalName().equals("countryName")) {
final CsdlAnnotation annotation = new CsdlAnnotation();
annotation.setTerm("Immutable");
annotation.setExpression(new CsdlConstantExpression(ConstantExpressionType.Bool, "true"));
property.addAnnotations(Collections.singletonList(annotation));
}
}
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {}
@Override
public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {}
}
private interface AnnotatedMember extends Member, AnnotatedElement {
}
private void createDefaultCut() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddableType("PostalAddressData"),
"countryName");
cut = new IntermediateDescriptionProperty(nameBuilder, jpaAttribute, et, helper.schema);
cut.lazyBuildEdmItem();
}
private Attribute<?, ?> createAttributeMock(final boolean association, final boolean associationName,
final int languageFields) {
final Attribute<?, ?> attribute = mock(Attribute.class);
final ManagedType<?> managedType = mock(ManagedType.class);
final Member member = mock(AnnotatedMember.class);
when(attribute.getName()).thenReturn("WithLocationField");
when(attribute.getJavaMember()).thenReturn(member);
when(attribute.getDeclaringType()).thenAnswer(new Answer<ManagedType<?>>() {
@Override
public ManagedType<?> answer(final InvocationOnMock invocation) throws Throwable {
return managedType;
}
});
when(attribute.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return Country.class;
}
});
when(managedType.getJavaType()).thenAnswer(new Answer<Class<BusinessPartner>>() {
@Override
public Class<BusinessPartner> answer(final InvocationOnMock invocation) throws Throwable {
return BusinessPartner.class;
}
});
if (association) {
final EdmDescriptionAssociation a = mock(EdmDescriptionAssociation.class);
when(((AnnotatedElement) member).getAnnotation(EdmDescriptionAssociation.class)).thenReturn(a);
if (associationName)
when(a.descriptionAttribute()).thenReturn("name");
if (languageFields > 0)
when(a.languageAttribute()).thenReturn("language");
if (languageFields > 1)
when(a.localeAttribute()).thenReturn("location");
}
return attribute;
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAQueryExtensionProviderTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAQueryExtensionProviderTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static java.util.Objects.requireNonNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import java.util.Map;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.From;
import org.junit.jupiter.api.Test;
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.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.EmptyQueryExtensionProvider;
class JPAQueryExtensionProviderTest {
@Test
void checkReturnsDefaultConstructor() throws ODataJPAModelException {
assertNotNull(new JPAQueryExtensionProvider<>(EmptyQueryExtensionProvider.class)
.getConstructor());
}
@Test
void checkThrowsExceptionTwoConstructors() {
assertThrows(ODataJPAModelException.class, () -> new JPAQueryExtensionProvider<>(
ExtensionProviderWithTwoConstructors.class).getConstructor());
}
@Test
void checkThrowsExceptionWrongParameter() {
assertThrows(ODataJPAModelException.class, () -> new JPAQueryExtensionProvider<>(
ExtensionProviderWithWrongParameter.class).getConstructor());
}
@Test
void checkReturnsConstructorWithHeaderAsParameter() throws ODataJPAModelException {
assertNotNull(new JPAQueryExtensionProvider<>(ExtensionProviderWithAllowedParameter.class).getConstructor());
}
private static class ExtensionProviderWithTwoConstructors implements EdmQueryExtensionProvider {
@SuppressWarnings("unused")
private final String dummy;
@Override
public Expression<Boolean> getFilterExtension(final CriteriaBuilder cb, final From<?, ?> from) {
return null;
}
@SuppressWarnings("unused")
public ExtensionProviderWithTwoConstructors(final String dummy) {
this.dummy = dummy;
}
@SuppressWarnings("unused")
public ExtensionProviderWithTwoConstructors() {
this.dummy = "Hello";
}
}
private static class ExtensionProviderWithAllowedParameter implements EdmQueryExtensionProvider {
@SuppressWarnings("unused")
private final Map<String, List<String>> header;
@SuppressWarnings("unused")
private final JPARequestParameterMap parameter;
@Override
public Expression<Boolean> getFilterExtension(final CriteriaBuilder cb, final From<?, ?> from) {
return null;
}
@SuppressWarnings("unused")
public ExtensionProviderWithAllowedParameter(final JPAHttpHeaderMap header,
final JPARequestParameterMap parameter) {
this.header = requireNonNull(header);
this.parameter = requireNonNull(parameter);
}
}
private static class ExtensionProviderWithWrongParameter implements EdmQueryExtensionProvider {
@SuppressWarnings("unused")
private final String header;
@Override
public Expression<Boolean> getFilterExtension(final CriteriaBuilder cb, final From<?, ?> from) {
return null;
}
@SuppressWarnings("unused")
public ExtensionProviderWithWrongParameter(final String header) {
this.header = header;
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateSchemaTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateSchemaTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.Metamodel;
import org.apache.olingo.commons.api.edm.EdmEnumType;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.errormodel.MissingCardinalityAnnotation;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.AccessRights;
import com.sap.olingo.jpa.processor.core.testmodel.UserType;
import com.sap.olingo.jpa.processor.core.util.TestDataConstants;
class IntermediateSchemaTest extends TestMappingRoot {
private Reflections reflections;
private IntermediateAnnotationInformation annotationInfo;
@BeforeEach
void setup() {
reflections = mock(Reflections.class);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class,
AccessRights.class,
UserType.class)));
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
}
@Test
void checkSchemaCanBeCreated() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertNotNull(schema);
}
@Test
void checkSchemaGetAllEntityTypes() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertEquals(TestDataConstants.NO_ENTITY_TYPES.value, schema.getEdmItem().getEntityTypes().size(),
"Wrong number of entities");
}
@Test
void checkSchemaGetEntityTypeByNameNotNull() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertNotNull(schema.getEdmItem().getEntityType("BusinessPartner"));
}
@Test
void checkSchemaGetEntityTypeByNameRightEntity() throws ODataJPAModelException {
final EdmEnumType enumType = mock(EdmEnumType.class);
final FullQualifiedName fqn = new FullQualifiedName(ADMIN_CANONICAL_NAME, ADDR_CANONICAL_NAME);
when(enumType.getFullQualifiedName()).thenReturn(fqn);
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertEquals("BusinessPartner", schema.getEdmItem().getEntityType("BusinessPartner").getName());
}
@Test
void checkSchemaGetAllComplexTypes() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
// ChangeInformation,CommunicationData,AdministrativeInformation,PostalAddressData
assertEquals(TestDataConstants.NO_COMPLEX_TYPES.value, schema.getEdmItem().getComplexTypes().size(),
"Wrong number of complex types");
}
@Test
void checkSchemaGetComplexTypeByNameNotNull() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertNotNull(schema.getEdmItem().getComplexType("CommunicationData"));
}
@Test
void checkSchemaGetComplexTypeByNameRightEntity() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertEquals("CommunicationData", schema.getEdmItem().getComplexType("CommunicationData").getName());
}
@Test
void checkSchemaGetAllFunctions() throws ODataJPAModelException {
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
assertEquals(10, schema.getEdmItem().getFunctions().size(), "Wrong number of entities");
}
@Test
void checkSchemaGetEnumerationTypeByType() throws ODataJPAModelException {
final EdmEnumType type = mock(EdmEnumType.class);
final FullQualifiedName fqn = new FullQualifiedName(PUNIT_NAME, "ABCClassification");
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
when(type.getFullQualifiedName()).thenReturn(fqn);
assertNotNull(schema.getEnumerationType(type));
}
@Test
void checkSchemaGetEnumerationTypeByTypeNotFound() throws ODataJPAModelException {
final EdmEnumType type = mock(EdmEnumType.class);
final FullQualifiedName fqn = new FullQualifiedName(PUNIT_NAME, "Classification");
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf
.getMetamodel(), reflections, annotationInfo);
when(type.getFullQualifiedName()).thenReturn(fqn);
assertNull(schema.getEnumerationType(type));
}
@Test
void checkSchemaWrapsException() throws ODataJPAModelException {
final Metamodel jpaModel = mock(Metamodel.class);
final EntityType<?> jpaEt = mock(EntityType.class);
when(jpaModel.getEmbeddables()).thenReturn(Collections.emptySet());
when(jpaModel.getEntities()).thenReturn(Collections.singleton(jpaEt));
doReturn(MissingCardinalityAnnotation.class).when(jpaEt).getJavaType();
when(jpaEt.getDeclaredAttributes()).thenThrow(NullPointerException.class);
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaModel,
reflections, annotationInfo);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class, () -> schema.lazyBuildEdmItem());
assertTrue(act.getCause() instanceof NullPointerException);
}
@Test
void checkSchemaODataJPAModelExceptionNotWrapped() throws ODataJPAModelException {
final Metamodel jpaModel = mock(Metamodel.class);
final EntityType<?> jpaEt = mock(EntityType.class);
when(jpaModel.getEmbeddables()).thenReturn(Collections.emptySet());
when(jpaModel.getEntities()).thenReturn(Collections.singleton(errorEmf.getMetamodel().entity(
MissingCardinalityAnnotation.class)));
doReturn(MissingCardinalityAnnotation.class).when(jpaEt).getJavaType();
final IntermediateSchema schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaModel,
reflections, annotationInfo);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class, () -> schema.lazyBuildEdmItem());
assertNull(act.getCause());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestOffsetDateTimeConverter.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestOffsetDateTimeConverter.java | /**
*
*/
package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.converter.OffsetDateTimeConverter;
/**
* @author Oliver Grande
* Created: 09.03.2020
*
*/
class TestOffsetDateTimeConverter {
private OffsetDateTimeConverter cut;
@BeforeEach
void setup() {
cut = new OffsetDateTimeConverter();
}
@Test
void checkConvertToDatabaseColumnReturnNullOnNull() {
assertNull(cut.convertToDatabaseColumn(null));
}
@Test
void checkConvertToEntityAttributeReturnNullOnNull() {
assertNull(cut.convertToEntityAttribute(null));
}
@Test
void checkConvertToDatabaseColumnReturnConvertedOnNonNull() {
final ZonedDateTime time = ZonedDateTime
.of(LocalDateTime.of(2020, 10, 20, 6, 23, 10), ZoneId.of(ZoneId.SHORT_IDS.get("ECT")));
final OffsetDateTime act = cut.convertToDatabaseColumn(time);
assertEquals("2020-10-20T06:23:10+02:00", act.toString());
}
@Test
void checkConvertToEntityAttributeReturnConvertedOnNonNull() {
final OffsetDateTime time = OffsetDateTime.of(
LocalDateTime.of(2020, 10, 20, 6, 23), ZoneOffset.ofHours(3));
final ZonedDateTime act = cut.convertToEntityAttribute(time);
assertEquals(time, act.toOffsetDateTime());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAPathTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAPathTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_MIXED_PART_OF_GROUP;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerWithGroups;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
class JPAPathTest extends TestMappingRoot {
private JPAEntityType organization;
private JPAEntityType bupaWithGroup;
private TestHelper helper;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
organization = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME), helper
.getEntityType(Organization.class), helper.schema);
bupaWithGroup = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
helper.getEntityType(BusinessPartnerWithGroups.class), helper.schema);
}
@Test
void checkOnePathElementAlias() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Name1");
assertEquals("Name1", cut.getAlias());
}
@Test
void checkOnePathElementPathSize() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Name1");
assertEquals(1, cut.getPath().size());
}
@Test
void checkOnePathElementElement() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Name1");
assertEquals("name1", cut.getPath().get(0).getInternalName());
}
@Test
void checkOnePathElementFromSuperTypeAlias() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Type");
assertEquals("Type", cut.getAlias());
}
@Test
void checkTwoPathElementAlias() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Address/Country");
assertEquals("Address/Country", cut.getAlias());
}
@Test
void checkTwoPathElementPathSize() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Address/Country");
assertEquals(2, cut.getPath().size());
}
@Test
void checkTwoPathElementPathElements() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Address/Country");
assertEquals("address", cut.getPath().get(0).getInternalName());
assertEquals("country", cut.getPath().get(1).getInternalName());
}
@Test
void checkThreePathElementAlias() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("AdministrativeInformation/Created/By");
assertEquals("AdministrativeInformation/Created/By", cut.getAlias());
}
@Test
void checkThreePathElementPathSize() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("AdministrativeInformation/Created/By");
assertEquals(3, cut.getPath().size());
}
@Test
void checkThreePathElementPathElements() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("AdministrativeInformation/Created/By");
assertEquals("administrativeInformation", cut.getPath().get(0).getInternalName());
assertEquals("created", cut.getPath().get(1).getInternalName());
assertEquals("by", cut.getPath().get(2).getInternalName());
}
@Test
void checkIsPartOfGroupReturnsTrueOnNotAnnotated() throws ODataJPAModelException {
final JPAPath act = bupaWithGroup.getPath("Type");
assertTrue(act.isPartOfGroups(Arrays.asList("Test")));
}
@Test
void checkIsPartOfGroupReturnsTrueOnAnnotatedBelongsToIt() throws ODataJPAModelException {
final JPAPath act = bupaWithGroup.getPath("Country");
assertTrue(act.isPartOfGroups(Arrays.asList("Person")));
}
@Test
void checkIsPartOfGroupCheckTwice() throws ODataJPAModelException {
final JPAPath act = bupaWithGroup.getPath("Country");
assertTrue(act.isPartOfGroups(Arrays.asList("Person")));
assertTrue(act.isPartOfGroups(Arrays.asList("Person")));
}
@Test
void checkIsPartOfGroupReturnsFalseOnAnnotatedDoesNotBelongsToIt() throws ODataJPAModelException {
final JPAPath act = bupaWithGroup.getPath("Country");
assertFalse(act.isPartOfGroups(Arrays.asList("Test")));
}
@Test
void checkIsPartOfGroupReturnsFalseOnAnnotatedComplex() throws ODataJPAModelException {
final JPAPath act = bupaWithGroup.getPath("CommunicationData/Email");
assertFalse(act.isPartOfGroups(Arrays.asList("Test")));
}
@Test
void checkIsPartOfGroupReturnsTrueOnNotAnnotatedComplex() throws ODataJPAModelException {
final JPAPath act = organization.getPath("CommunicationData/Email");
assertTrue(act.isPartOfGroups(Arrays.asList("Test")));
}
@Test
void checkThrowsExceptionOnInconsistentGroups1() {
final List<JPAElement> attributes = new ArrayList<>(2);
final IntermediateProperty complex = mock(IntermediateProperty.class);
when(complex.isPartOfGroup()).thenReturn(true);
when(complex.getUserGroups()).thenReturn(Arrays.asList("Test", "Dummy"));
attributes.add(complex);
final IntermediateProperty primitive = mock(IntermediateProperty.class);
when(primitive.isPartOfGroup()).thenReturn(true);
when(primitive.getUserGroups()).thenReturn(Arrays.asList("Dummy"));
attributes.add(primitive);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new JPAPathImpl("Communication/Email", "Telecom.Email", attributes));
assertEquals(NOT_SUPPORTED_MIXED_PART_OF_GROUP.getKey(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkThrowsExceptionOnInconsistentGroups2() {
final List<JPAElement> attributes = new ArrayList<>(2);
final IntermediateProperty complex = mock(IntermediateProperty.class);
when(complex.isPartOfGroup()).thenReturn(true);
when(complex.getUserGroups()).thenReturn(Arrays.asList("Test", "Dummy"));
attributes.add(complex);
final IntermediateProperty primitive = mock(IntermediateProperty.class);
when(primitive.isPartOfGroup()).thenReturn(true);
when(primitive.getUserGroups()).thenReturn(Arrays.asList("Dummy", "Willi"));
attributes.add(primitive);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new JPAPathImpl("Communication/Email", "Telecom.Email", attributes));
assertEquals(NOT_SUPPORTED_MIXED_PART_OF_GROUP.getKey(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkThrowsExceptionOnInconsistentGroups3() {
final List<JPAElement> attributes = new ArrayList<>(2);
final IntermediateProperty complex = mock(IntermediateProperty.class);
when(complex.isPartOfGroup()).thenReturn(true);
when(complex.getUserGroups()).thenReturn(Arrays.asList("Test", "Dummy"));
attributes.add(complex);
final IntermediateProperty primitive = mock(IntermediateProperty.class);
when(primitive.isPartOfGroup()).thenReturn(true);
when(primitive.getUserGroups()).thenReturn(Arrays.asList("Dummy", "Test", "Willi"));
attributes.add(primitive);
final ODataJPAModelException act = assertThrows(ODataJPAModelException.class,
() -> new JPAPathImpl("Communication/Email", "Telecom.Email", attributes));
assertEquals(NOT_SUPPORTED_MIXED_PART_OF_GROUP.getKey(), act.getId());
assertFalse(act.getMessage().isEmpty());
}
@Test
void checkTwoNotEqualIfAliasNotEqual() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Address/Country");
final JPAPath act = new JPAPathImpl("Address", cut.getDBFieldName(), cut.getPath());
assertNotEquals(act, cut);
}
@Test
void checkTwoNotEqualIfElementListNotEqual() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Address/Country");
final List<JPAElement> pathList = new ArrayList<>(cut.getPath());
pathList.remove(0);
final JPAPath act = new JPAPathImpl("Address/Country", cut.getDBFieldName(), pathList);
assertNotEquals(act, cut);
}
@Test
void checkTwoEqualIfSame() throws ODataJPAModelException {
final JPAPath cut = organization.getPath("Address/Country");
assertEquals(cut, cut);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateStructuredTypeTransientPluralAttributeTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateStructuredTypeTransientPluralAttributeTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.persistence.metamodel.ManagedType;
import jakarta.persistence.metamodel.PluralAttribute.CollectionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class IntermediateStructuredTypeTransientPluralAttributeTest extends TestMappingRoot {
private IntermediateStructuredType.TransientPluralAttribute<?, ?, ?> cut;
private ManagedType<?> managedType;
private Field attribute;
private TestHelper helper;
@SuppressWarnings("unused")
private Map<String, String> mapAttribute;
@SuppressWarnings("unused")
private Set<String> setAttribute;
@SuppressWarnings("unused")
private List<String> listAttribute;
@SuppressWarnings("unused")
private Collection<String> collAttribute;
@BeforeEach
void setup() throws ODataJPAModelException, SecurityException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
managedType = mock(ManagedType.class);
}
@TestFactory
Collection<DynamicTest> checkGetCollectionType() {
return Arrays.asList(
dynamicTest("Map", () -> executeGetCollectionTypeCheck(CollectionType.MAP, "mapAttribute")),
dynamicTest("Set", () -> executeGetCollectionTypeCheck(CollectionType.SET, "setAttribute")),
dynamicTest("List", () -> executeGetCollectionTypeCheck(CollectionType.LIST, "listAttribute")),
dynamicTest("Default", () -> executeGetCollectionTypeCheck(CollectionType.COLLECTION, "collAttribute")));
}
void executeGetCollectionTypeCheck(final CollectionType type, final String attributeName) {
try {
attribute = this.getClass().getDeclaredField(attributeName);
cut = new IntermediateStructuredType.TransientPluralAttribute<>(managedType, attribute, helper.schema);
assertEquals(type, cut.getCollectionType());
} catch (NoSuchFieldException | SecurityException e) {
fail();
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateSimplePropertyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateSimplePropertyTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.PROPERTY_PRECISION_NOT_IN_RANGE;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.TRANSIENT_CALCULATOR_TOO_MANY_CONSTRUCTORS;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.TRANSIENT_CALCULATOR_WRONG_PARAMETER;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.TRANSIENT_KEY_NOT_SUPPORTED;
import static com.sap.olingo.jpa.processor.core.util.Assertions.assertException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Member;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import jakarta.persistence.Column;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.Attribute.PersistentAttributeType;
import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.ManagedType;
import jakarta.persistence.metamodel.SingularAttribute;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlTypeDefinition;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmGeospatial;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtectedBy;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtections;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
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.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.util.AnnotationTestHelper;
import com.sap.olingo.jpa.metadata.core.edm.mapper.util.MemberDouble;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.GeneralProperty;
import com.sap.olingo.jpa.metadata.odata.v4.core.terms.Terms;
import com.sap.olingo.jpa.metadata.odata.v4.general.Aliases;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCoreAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.errormodel.TeamWithTransientCalculatorConstructorError;
import com.sap.olingo.jpa.processor.core.errormodel.TeamWithTransientCalculatorError;
import com.sap.olingo.jpa.processor.core.errormodel.TeamWithTransientKey;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription;
import com.sap.olingo.jpa.processor.core.testmodel.AnnotationsParent;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected;
import com.sap.olingo.jpa.processor.core.testmodel.Collection;
import com.sap.olingo.jpa.processor.core.testmodel.Comment;
import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData;
import com.sap.olingo.jpa.processor.core.testmodel.ComplexBaseType;
import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
import com.sap.olingo.jpa.processor.core.testmodel.PersonImage;
import com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData;
import com.sap.olingo.jpa.processor.core.testmodel.RestrictedEntityComplex;
import com.sap.olingo.jpa.processor.core.testmodel.RestrictedEntityUnrestrictedSource;
import com.sap.olingo.jpa.processor.core.testmodel.User;
class IntermediateSimplePropertyTest extends TestMappingRoot {
private TestHelper helper;
private TestHelper errorHelper;
private JPAEdmMetadataPostProcessor processor;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
errorHelper = new TestHelper(errorEmf.getMetamodel(), ERROR_PUNIT);
processor = mock(JPAEdmMetadataPostProcessor.class);
}
@Test
void checkPropertyCanBeCreated() throws ODataJPAModelException {
final EmbeddableType<?> et = helper.getEmbeddableType(CommunicationData.class);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(et, "landlinePhoneNumber");
assertNotNull(new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaAttribute,
helper.schema));
}
@Test
void checkGetPropertyName() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals("Type", property.getEdmItem().getName(), "Wrong name");
}
@Test
void checkGetPropertyDBFieldNameFromColumn() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals("\"Type\"", property.getDBFieldName(), "Wrong name");
}
@Test
void checkGetPropertyDBFieldNameNotProvidedDifferentNameBuilder() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getComplexType(ComplexBaseType.class),
"oneAttribute");
final var property = new IntermediateSimpleProperty(new LocalJPAEdmNameBuilder(), jpaAttribute, helper.schema);
assertEquals("ONE_ATTRIBUTE", property.getDBFieldName(), "Wrong name");
}
@Test
void checkGetPropertyDBFieldNameNotProvided() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getComplexType(ComplexBaseType.class),
"oneAttribute");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals("\"oneAttribute\"", property.getDBFieldName(), "Wrong name");
}
@Test
void checkGetPropertySimpleType() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(EdmPrimitiveTypeKind.String.getFullQualifiedName().getFullQualifiedNameAsString(),
property.getEdmItem().getType(), "Wrong type");
}
@Test
void checkGetPropertyComplexType() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"communicationData");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(PUNIT_NAME + ".CommunicationData", property.getEdmItem().getType(), "Wrong type");
}
@Test
void checkGetPropertyEnumTypeWithoutConverter() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Organization.class), "aBCClass");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals("com.sap.olingo.jpa.ABCClassification", property.getEdmItem().getType(), "Wrong type");
}
@Test
void checkGetPropertyEnumTypeWithoutConverterMustNotHaveMapper() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Organization.class), "aBCClass");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNull(property.getEdmItem().getMapping());
}
@Test
void checkGetPropertyEnumTypeWithConverter() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "accessRights");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals("com.sap.olingo.jpa.AccessRights", property.getEdmItem().getType(), "Wrong type");
}
@Test
void checkGetPropertyEnumTypeWithEnumerated() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(User.class), "userType");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(String.class, property.getDbType());
assertNotNull(property.getEdmItem());
}
@Test
void checkGetPropertyIgnoreFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type");
final IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertFalse(property.ignore());
}
@Test
void checkGetPropertyIgnoreTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"customString1");
final IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertTrue(property.ignore());
}
@Test
void checkGetPropertyFacetsNullableTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"customString1");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertTrue(property.getEdmItem().isNullable());
}
@Test
void checkGetPropertyFacetsNullableTrueComplex() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(
helper.getEmbeddableType(PostalAddressData.class), "pOBox");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertTrue(property.getEdmItem().isNullable());
}
@Test
void checkGetPropertyFacetsNullableFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "eTag");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertFalse(property.getEdmItem().isNullable());
}
@Test
void checkGetPropertyIsEtagTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "eTag");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertTrue(property.isEtag());
}
@Test
void checkGetPropertyIsEtagFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertFalse(property.isEtag());
}
@Test
void checkGetPropertyMaxLength() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(Integer.valueOf(1), property.getEdmItem().getMaxLength());
}
@Test
void checkGetPropertyMaxLengthNullForClob() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getComplexType("DummyEmbeddedToIgnore"), "command");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNull(property.getEdmItem().getMaxLength());
}
@Test
void checkGetPropertyPrecisionDecimal() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customNum1");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(Integer.valueOf(16), property.getEdmItem().getPrecision());
}
@Test
void checkGetPropertyScaleDecimal() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customNum1");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(Integer.valueOf(5), property.getEdmItem().getScale());
}
@Test
void checkGetPropertyPrecisionTime() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"creationDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(Integer.valueOf(2), property.getEdmItem().getPrecision());
}
@Test
void checkGetPropertyMapper() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"creationDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNotNull(property.getEdmItem().getMapping());
assertEquals(Timestamp.class, property.getEdmItem().getMapping().getMappedJavaClass());
}
@Test
void checkGetPropertyMapperWithConverter() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Collection.class), "localDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNotNull(property.getEdmItem().getMapping());
assertEquals(java.util.Date.class, property.getEdmItem().getMapping().getMappedJavaClass());
}
@Test
void checkGetNoPropertyMapperForClob() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Comment.class), "text");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute,
helper.schema);
assertNull(property.getEdmItem().getMapping());
}
@Test
void checkPostProcessorCalled() throws ODataJPAModelException {
IntermediateSimpleProperty.setPostProcessor(processor);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"creationDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
property.getEdmItem();
verify(processor, atLeastOnce()).processProperty(property, BUPA_CANONICAL_NAME);
}
@Test
void checkPostProcessorAnnotationAdded() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateSimpleProperty.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"customString1");
final var cut = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertEquals(1L, cut.getEdmItem().getAnnotations().stream().filter(a -> a.getTerm().equals("Immutable")).count());
}
@Test
void checkGetConverterReturnedConversionRequired() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"creationDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNotNull(property.getConverter());
}
@Test
void checkGetConverterNullDBTypeEqJavaType() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "customString1");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNull(property.getConverter());
}
@Test
void checkGetConverterNullConversionNotRequired() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(DummyToBeIgnored.class), "uuid");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNull(property.getConverter());
}
@Test
void checkGetRawConverterReturnedConversionRequired() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"creationDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNotNull(property.getRawConverter());
}
@Test
void checkGetRawConverterNullNoConverterDefined() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "customString2");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNull(property.getRawConverter());
}
@Test
void checkGetRawConverterReturnsConversionNotRequired() throws ODataJPAModelException {
final var postProcessorDouble = new PostProcessorSetName();
IntermediateModelElement.setPostProcessor(postProcessorDouble);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(DummyToBeIgnored.class), "uuid");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertNotNull(property.getRawConverter());
}
@Test
void checkGetPropertyDefaultValue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEmbeddableType(PostalAddressData.class),
"regionCodePublisher");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertEquals("ISO", property.getEdmItem().getDefaultValue());
}
@Test
void checkGetPropertyDefaultValueIgnoredOnAbstractClass() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"iD");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertNull(property.getEdmItem().getDefaultValue());
}
@Test
void checkGetPropertyIsStream() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(PersonImage.class),
"image");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertTrue(property.isStream());
}
@Test
void checkGetPropertyIsTransientTrue() throws ODataJPAModelException, NoSuchFieldException, SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertTrue(property.isTransient());
}
@Test
void checkGetPropertyIsTransientFalse() throws ODataJPAModelException, NoSuchFieldException,
SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("lastName"));
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertFalse(property.isTransient());
}
@Test
void checkGetPropertyIsTransientThrowExceptionOnBeingKey() throws NoSuchFieldException, SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(errorHelper
.getEntityType(TeamWithTransientKey.class), TeamWithTransientKey.class.getDeclaredField("name"));
assertException(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(errorNameBuilder, jpaAttribute, errorHelper.schema),
TRANSIENT_KEY_NOT_SUPPORTED.getKey());
}
@Test
void checkGetPropertyGetCalculatorNullOnPersistentProperty() throws ODataJPAModelException,
NoSuchFieldException,
SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("lastName"));
final var property = new IntermediateSimpleProperty(nameBuilder, jpaAttribute,
helper.schema);
assertNull(property.getCalculatorConstructor());
}
@Test
void checkGetPropertyGetCalculatorTransientNotNull() throws ODataJPAModelException, NoSuchFieldException,
SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertNotNull(property.getCalculatorConstructor());
}
@Test
void checkTransientIsCollectionFalse() throws NoSuchFieldException, SecurityException {
final SingularAttribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
assertFalse(jpaAttribute.isCollection());
}
@Test
void checkTransientBindableTypeNull() throws NoSuchFieldException, SecurityException {
final SingularAttribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
assertNull(jpaAttribute.getBindableType());
}
@Test
void checkTransientBindableJavaTypeNull() throws NoSuchFieldException, SecurityException {
final SingularAttribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
assertNull(jpaAttribute.getBindableJavaType());
}
@Test
void checkTransientTypeNull() throws NoSuchFieldException, SecurityException {
final SingularAttribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
assertNull(jpaAttribute.getType());
}
@Test
void checkTransientIsVersionFalse() throws NoSuchFieldException, SecurityException {
final SingularAttribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
assertFalse(jpaAttribute.isVersion());
}
@Test
void checkTransientIsOptionalTrue() throws NoSuchFieldException, SecurityException {
final SingularAttribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(helper
.getEntityType(Person.class), Person.class.getDeclaredField("fullName"));
assertTrue(jpaAttribute.isOptional());
}
@Test
void checkGetPropertyGetCalculatorThrowExceptionOnMultipleConstructors() throws NoSuchFieldException,
SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(errorHelper
.getEntityType(
TeamWithTransientCalculatorError.class), TeamWithTransientCalculatorError.class.getDeclaredField(
"completeName"));
assertException(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(errorNameBuilder, jpaAttribute, errorHelper.schema),
TRANSIENT_CALCULATOR_TOO_MANY_CONSTRUCTORS.getKey());
}
@Test
void checkGetPropertyGetCalculatorThrowExceptionOnWrongConstructors() throws NoSuchFieldException, SecurityException {
final Attribute<?, ?> jpaAttribute = new IntermediateStructuredType.TransientSingularAttribute<>(errorHelper
.getEntityType(
TeamWithTransientCalculatorConstructorError.class), TeamWithTransientCalculatorConstructorError.class
.getDeclaredField("completeName"));
assertException(ODataJPAModelException.class,
() -> new IntermediateSimpleProperty(errorNameBuilder, jpaAttribute, errorHelper.schema),
TRANSIENT_CALCULATOR_WRONG_PARAMETER.getKey());
}
@Test
void checkGetTypeBoxedForPrimitive() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(AdministrativeDivision.class),
"population");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertEquals(Long.class, property.getType());
}
@Test
void checkGetTypeBoxed() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(AdministrativeDivision.class),
"area");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertEquals(Long.class, property.getType());
}
@Test
void checkGetTypeConversionRequired() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class),
"creationDateTime");
final var property = new IntermediateSimpleProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema);
assertTrue(property.conversionRequired);
assertEquals(Timestamp.class, property.getType());
assertEquals(Timestamp.class, property.getDbType());
assertEquals(LocalDateTime.class, property.getJavaType());
}
@Test
void checkGetTypeConversionNotRequired() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class),
"birthDay");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertFalse(property.conversionRequired);
assertEquals(LocalDate.class, property.getType());
assertEquals(Date.class, property.getDbType());
assertEquals(LocalDate.class, property.getJavaType());
}
@Test
void checkTimestampWithoutPrecisionReturns0() throws ODataJPAModelException {
// If Precision missing EdmDateTimeOffset.internalValueToString throws an exception => pre-check
final Attribute<?, ?> jpaAttribute = mock(Attribute.class);
final ManagedType<?> jpaManagedType = mock(ManagedType.class);
when(jpaAttribute.getName()).thenReturn("start");
when(jpaAttribute.getPersistentAttributeType()).thenReturn(PersistentAttributeType.BASIC);
when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer<ManagedType<?>>() {
@Override
public ManagedType<?> answer(final InvocationOnMock invocation) throws Throwable {
return jpaManagedType;
}
});
when(jpaAttribute.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return Timestamp.class;
}
});
when(jpaManagedType.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return DummyToBeIgnored.class;
}
});
final var column = mock(Column.class);
final var annotations = mock(AnnotatedElement.class, withSettings().extraInterfaces(Member.class));
when(annotations.getAnnotation(Column.class)).thenReturn(column);
when(jpaAttribute.getJavaMember()).thenReturn((Member) annotations);
when(column.name()).thenReturn("Test");
final var property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertEquals(0, property.getEdmItem().getPrecision());
}
@Test
void checkGetPropertyHasProtectionFalse() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class),
"eTag");
final IntermediatePropertyAccess property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertFalse(property.hasProtection());
}
@Test
void checkGetPropertyHasProtectionTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class),
"userName");
final IntermediatePropertyAccess property = new IntermediateSimpleProperty(nameBuilder,
jpaAttribute, helper.schema);
assertTrue(property.hasProtection());
}
@Test
void checkGetPropertyProtectionSupportsWildCardTrue() throws ODataJPAModelException {
final Attribute<?, ?> jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class),
"userName");
| 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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateJavaActionTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateJavaActionTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmAction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.ODataAction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testaction.ActionWithOverload;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testaction.Actions;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaActions;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaEmConstructor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaPrivateConstructor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoParameterConstructor;
class IntermediateJavaActionTest extends TestMappingRoot {
private TestHelper helper;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
}
@Test
void checkInternalNameEqualMethodName() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertEquals("unboundWithImport", act.getInternalName());
}
@Test
void checkExternalNameEqualMethodName() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertEquals("UnboundWithImport", act.getExternalName());
}
@Test
void checkReturnsFalseForIsBound() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertNotNull(act.getEdmItem());
assertFalse(act.getEdmItem().isBound());
}
@Test
void checkReturnsTrueForIsBound() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
assertNotNull(act.getEdmItem());
assertTrue(act.getEdmItem().isBound());
assertEquals(PUNIT_NAME + ".Person", act.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkReturnsEntitySetPathForBound() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithEntitySetPath");
assertNotNull(act.getEdmItem());
assertTrue(act.getEdmItem().isBound());
assertEquals("Person/Roles", act.getEdmItem().getEntitySetPath());
}
@Test
void checkReturnsGivenEntitySetTypeIfBound() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
assertNotNull(act.getEdmItem());
assertTrue(act.getEdmItem().isBound());
assertEquals(PUNIT_NAME + ".Person", act.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
assertEquals("Edm.Decimal", act.getEdmItem().getParameters().get(1).getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkReturnsExternalName() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
assertNotNull(act.getEdmItem());
assertEquals("BoundNoImport", act.getEdmItem().getName());
}
@Test
void checkReturnsTrueForHasActionImportIfUnbound() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertTrue(act.hasImport());
}
@Test
void checkReturnsFalseForHasActionImportIfNotSet() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
assertFalse(act.hasImport());
}
@Test
void checkEmptyParameterNameThrowsException() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "nameEmpty");
assertThrows(ODataJPAModelException.class, act::getParameter);
}
@Test
void checkReturnsReturnTypeConvertedPrimitiveReturnType() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertNotNull(act.getEdmItem());
assertNotNull(act.getEdmItem().getReturnType());
assertEquals("Edm.Int32", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsReturnTypeNullForVoid() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
assertNotNull(act.getEdmItem());
assertNull(act.getEdmItem().getReturnType());
}
@Test
void checkReturnsReturnTypeEmbeddableType() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddable");
assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsEntityTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEntity");
assertEquals("com.sap.olingo.jpa.Person", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsEnumerationTypeAsReturnType() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEnumeration");
assertEquals("com.sap.olingo.jpa.ABCClassification", act.getEdmItem().getReturnType().getType());
}
@Test
void checkReturnsReturnTypeCollectionOfPrimitive() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnCollection");
assertEquals("Edm.String", act.getEdmItem().getReturnType().getType());
assertTrue(act.getEdmItem().getReturnType().isCollection(), act.toString() + " " + act.getResultParameter());
}
@Test
void checkReturnsReturnTypeCollectionOfEmbeddable() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddableCollection");
assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType());
assertTrue(act.getEdmItem().getReturnType().isCollection());
}
@Test
void checkReturnsReturnTypeFacetForNumbers() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundReturnFacet");
assertFalse(act.getEdmItem().getReturnType().isNullable());
assertEquals(20, act.getEdmItem().getReturnType().getPrecision());
assertEquals(5, act.getEdmItem().getReturnType().getScale());
}
@Test
void checkReturnsReturnTypeFacetForNonNumbers() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertNull(act.getEdmItem().getReturnType().getPrecision());
assertNull(act.getEdmItem().getReturnType().getScale());
assertNull(act.getEdmItem().getReturnType().getMaxLength());
}
@Test
void checkReturnsReturnTypeFacetForStringsAndGeo() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "calculateLocation");
assertEquals(60, act.getEdmItem().getReturnType().getMaxLength());
assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getReturnType().getSrid().getDimension());
assertEquals("4326", act.getEdmItem().getReturnType().getSrid().toString());
}
@Test
void checkReturnsParameterConvertPrimitiveTypes() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertNotNull(act.getEdmItem());
assertNotNull(act.getEdmItem().getParameters());
assertEquals(2, act.getEdmItem().getParameters().size());
assertNotNull(act.getEdmItem().getParameter("A"));
assertNotNull(act.getEdmItem().getParameter("B"));
assertEquals("Edm.Int16", act.getEdmItem().getParameter("A").getType());
assertEquals("Edm.Int32", act.getEdmItem().getParameter("B").getType());
}
@Test
void checkReturnsParameterFacetForNumbers() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
assertNotNull(act.getParameter());
assertEquals(34, act.getParameter().get(1).getPrecision());
assertEquals(10, act.getParameter().get(1).getScale());
assertNotNull(act.getEdmItem().getParameters());
assertEquals(34, act.getEdmItem().getParameters().get(1).getPrecision());
assertEquals(10, act.getEdmItem().getParameters().get(1).getScale());
}
@Test
void checkReturnsParameterFacetForNonNumbers() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertNotNull(act.getEdmItem().getParameters());
assertNull(act.getEdmItem().getParameters().get(1).getPrecision());
assertNull(act.getEdmItem().getParameters().get(1).getScale());
assertNull(act.getEdmItem().getParameters().get(1).getMaxLength());
}
@Test
void checkReturnsParameterFacetForStringsAndGeo() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "calculateLocation");
assertNotNull(act.getParameter());
assertEquals(100, act.getParameter().get(0).getMaxLength());
assertEquals(Dimension.GEOGRAPHY, act.getParameter().get(0).getSrid().getDimension());
assertEquals("4326", act.getParameter().get(0).getSrid().toString());
assertNotNull(act.getEdmItem().getParameters());
assertEquals(100, act.getEdmItem().getParameters().get(0).getMaxLength());
assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getParameters().get(0).getSrid().getDimension());
assertEquals("4326", act.getEdmItem().getParameters().get(0).getSrid().toString());
}
@Test
void checkReturnsParameterFacetWithMapping() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundReturnFacet");
assertNotNull(act.getEdmItem().getParameters());
assertNotNull(act.getEdmItem().getParameters().get(0).getMapping());
assertEquals(Short.class, act.getEdmItem().getParameters().get(0).getMapping().getMappedJavaClass());
}
@Test
void checkReturnsEnumerationTypeAsParameter() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEnumeration");
assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN()
.getFullQualifiedNameAsString());
}
@Test
void checkProvidesAllParameter() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
final List<JPAParameter> actParams = act.getParameter();
assertEquals(2, actParams.size());
}
@Test
void checkProvidesParameterByDeclared() throws ODataJPAModelException, NoSuchMethodException,
SecurityException {
final Method method = ExampleJavaActions.class.getMethod("unboundWithImport", short.class, int.class);
final Parameter[] params = method.getParameters();
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
assertNotNull(act.getParameter(params[0]));
assertEquals("A", act.getParameter(params[0]).getName());
assertNotNull(act.getParameter(params[1]));
assertEquals("B", act.getParameter(params[1]).getName());
}
@Test
void checkExceptConstructorWithoutParameter() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport");
act.getEdmItem();
assertNotNull(act.getConstructor());
}
@Test
void checkExceptConstructorWithEntityManagerParameter() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaEmConstructor.class, "mul");
assertNotNull(act.getConstructor());
assertEquals(1, act.getConstructor().getParameterTypes().length);
}
@Test
void checkThrowsExceptionOnPrivateConstructor() {
assertThrows(ODataJPAModelException.class, () -> {
createAction(ExampleJavaPrivateConstructor.class, "mul");
});
}
@Test
void checkThrowsExceptionOnNoConstructorAsSpecified() {
assertThrows(ODataJPAModelException.class, () -> {
createAction(ExampleJavaTwoParameterConstructor.class, "mul");
});
}
@TestFactory
Stream<DynamicTest> testCreateActionThrowsException() {
final Class<ExampleJavaActions> clazz = ExampleJavaActions.class;
return Stream.of("errorNonPrimitiveParameter",
"returnCollectionWithoutReturnType",
"boundWithOutBindingParameter",
"boundWithOutParameter",
"boundBindingParameterSecondParameter",
"errorUnboundWithEntitySetPath",
"errorPrimitiveTypeWithEntitySetPath")
.map(name -> createActionNoThrow(clazz, name))
.map(function -> dynamicTest(function.internalName,
() -> assertThrows(ODataJPAModelException.class, function::getEdmItem)
));
}
@Test
void checkGetReturnTypeReturnsCsdlReturnType() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEntity");
act.getEdmItem();
assertNotNull(act.getReturnType());
assertEquals("Person", act.getReturnType().getTypeFQN().getName());
}
@Test
void checkGetReturnTypeReturnsNullForVoid() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
act.getEdmItem();
assertNull(act.getReturnType());
}
@Test
void checkIsBoundReturnsTrueForBound() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport");
act.getEdmItem();
assertTrue(act.isBound());
}
@Test
void checkConstructorWithThreeParameter() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ActionWithOverload.class, "baseAction");
assertNotNull(act.getConstructor());
assertEquals(3, act.getConstructor().getParameterCount());
}
@Test
void checkGetGroupsReturnsGiven() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(Actions.class, "protectedAction");
assertArrayEquals(new String[] { "Person" }, act.getUserGroups().toArray(new String[] {}));
}
@Test
void checkGetGroupsReturnsEmptyListIfNoProvided() throws ODataJPAModelException {
final IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddable");
assertTrue(act.getUserGroups().isEmpty());
}
private IntermediateJavaAction createAction(final Class<? extends ODataAction> clazz, final String method)
throws ODataJPAModelException {
for (final Method m : Arrays.asList(clazz.getMethods())) {
final EdmAction actionDescription = m.getAnnotation(EdmAction.class);
if (actionDescription != null && method.equals(m.getName())) {
return new IntermediateJavaAction(new JPADefaultEdmNameBuilder(PUNIT_NAME), actionDescription, m,
helper.schema);
}
}
return null;
}
private IntermediateJavaAction createActionNoThrow(final Class<? extends ODataAction> clazz, final String method) {
for (final Method m : Arrays.asList(clazz.getMethods())) {
final EdmAction actionDescription = m.getAnnotation(EdmAction.class);
if (actionDescription != null && method.equals(m.getName())) {
try {
return new IntermediateJavaAction(new JPADefaultEdmNameBuilder(PUNIT_NAME), actionDescription, m,
helper.schema);
} catch (final ODataJPAModelException e) {
fail(e.getMessage());
}
}
}
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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAServiceDocumentFactoryTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAServiceDocumentFactoryTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class JPAServiceDocumentFactoryTest {
private JPAServiceDocumentFactory cut;
@BeforeEach
void setup() {
cut = new JPAServiceDocumentFactory();
}
@Test
void testAs() throws ODataJPAModelException {
final var sd = mock(JPAServiceDocument.class);
assertEquals(sd, cut.asUserGroupRestricted(sd, List.of()));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateActionFactoryTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateActionFactoryTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.ODataAction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testaction.ActionWithOverload;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneAction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoActions;
class IntermediateActionFactoryTest extends TestMappingRoot {
private TestHelper helper;
private Reflections reflections;
private IntermediateActionFactory cut;
private Set<Class<? extends ODataAction>> javaActions;
@BeforeEach
void setUp() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
reflections = mock(Reflections.class);
cut = new IntermediateActionFactory();
javaActions = new HashSet<>();
when(reflections.getSubTypesOf(ODataAction.class)).thenReturn(javaActions);
}
@Test
void checkReturnEmptyMapIfReflectionsNull() throws ODataJPAModelException {
final Reflections reflections = null;
assertNotNull(cut.create(new JPADefaultEdmNameBuilder(PUNIT_NAME), reflections, helper.schema));
}
@Test
void checkReturnEmptyMapIfNoJavaActionsFound() throws ODataJPAModelException {
assertNotNull(cut.create(new JPADefaultEdmNameBuilder(PUNIT_NAME), reflections, helper.schema));
}
@Test
void checkReturnMapWithOneIfOneJavaActionsFound() throws ODataJPAModelException {
javaActions.add(ExampleJavaOneAction.class);
final Map<ODataActionKey, IntermediateJavaAction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(1, act.size());
}
@Test
void checkReturnMapWithTwoIfTwoJavaActionsFound() throws ODataJPAModelException {
javaActions.add(ExampleJavaTwoActions.class);
final Map<ODataActionKey, IntermediateJavaAction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(2, act.size());
}
@Test
void checkReturnMapWithWithJavaActionsFromTwoClassesFound() throws ODataJPAModelException {
javaActions.add(ExampleJavaOneAction.class);
javaActions.add(ExampleJavaTwoActions.class);
final Map<ODataActionKey, IntermediateJavaAction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(3, act.size());
}
@Test
void checkReturnMapWithWithOverloadedActions() throws ODataJPAModelException {
javaActions.add(ActionWithOverload.class);
final Map<ODataActionKey, IntermediateJavaAction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(3, act.size());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEntitySetTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEntitySetTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.processor.core.util.Assertions.assertListEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import jakarta.persistence.Entity;
import jakarta.persistence.metamodel.EntityType;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlNavigationPropertyBinding;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEntityType;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataPathNotFoundException;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.PropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.TermAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntitySet;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntitySetAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.util.AnnotationTestHelper;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.CountRestrictionsProperties;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.ExpandRestrictionsProperties;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.FilterRestrictionsProperties;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.Terms;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.UpdateMethod;
import com.sap.olingo.jpa.metadata.odata.v4.capabilities.terms.UpdateRestrictionsProperties;
import com.sap.olingo.jpa.metadata.odata.v4.general.Aliases;
import com.sap.olingo.jpa.metadata.odata.v4.provider.JavaBasedCapabilitiesAnnotationsProvider;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.AnnotationsParent;
import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
class IntermediateEntitySetTest extends TestMappingRoot {
private IntermediateSchema schema;
private Set<EntityType<?>> etList;
private JPADefaultEdmNameBuilder nameBuilder;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateReferences references;
@BeforeEach
void setup() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
final var reflections = mock(Reflections.class);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class)));
etList = emf.getMetamodel().getEntities();
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
references = mock(IntermediateReferences.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>(), references);
schema = new IntermediateSchema(nameBuilder, emf.getMetamodel(), reflections, annotationInfo);
}
@Test
void checkAnnotationSet() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new PostProcessor());
final var et = new IntermediateEntityType<>(nameBuilder,
getEntityType("AdministrativeDivisionDescription"), schema);
final var es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.getEdmItem().getAnnotations();
assertEquals(1, act.size());
assertEquals("Capabilities.TopSupported", act.get(0).getTerm());
}
@Test
void checkODataEntityTypeDiffers() throws ODataJPAModelException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType("BestOrganization"), schema);
final var es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var odataEt = es.getODataEntityType();
assertEquals("BusinessPartner", odataEt.getExternalName());
}
@Test
void checkODataEntityTypeSame() throws ODataJPAModelException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType("Organization"), schema);
final var es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var odataEt = es.getODataEntityType();
assertEquals("Organization", odataEt.getExternalName());
}
@Test
void checkEdmItemContainsODataEntityType() throws ODataJPAModelException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType("BestOrganization"), schema);
final var es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.getEdmItem();
assertEquals(et.buildFQN("BusinessPartner").getFullQualifiedNameAsString(), act.getType());
}
@Test
void checkConvertStringToPathWithSimplePath() throws ODataJPAModelException, ODataPathNotFoundException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
final IntermediateTopLevelEntity es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.convertStringToPath("type");
assertNotNull(act);
assertEquals("Type", act.getPathAsString());
}
@Test
void checkConvertStringToNavigationPathWithSimplePath() throws ODataJPAModelException, ODataPathNotFoundException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
final IntermediateTopLevelEntity es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.convertStringToNavigationPath("roles");
assertNotNull(act);
assertEquals("Roles", act.getPathAsString());
}
@Test
void checkJavaAnnotationsOneAnnotation() throws ODataJPAModelException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
final IntermediateTopLevelEntity es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.javaAnnotations(EdmEntityType.class.getPackage().getName());
assertEquals(2, act.size());
assertNotNull(act.get("EdmEntityType"));
assertNotNull(act.get("EdmFunctions"));
}
@Test
void checkJavaAnnotationsTwoAnnotations() throws ODataJPAModelException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
final IntermediateTopLevelEntity es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.javaAnnotations(Entity.class.getPackage().getName());
assertEquals(4, act.size());
assertNotNull(act.get("Table"));
assertNotNull(act.get("Entity"));
assertNotNull(act.get("Inheritance"));
assertNotNull(act.get("DiscriminatorColumn"));
}
@Test
void checkJavaAnnotationsNoAnnotations() throws ODataJPAModelException {
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(BusinessPartner.class), schema);
final IntermediateTopLevelEntity es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.javaAnnotations(Test.class.getPackage().toString());
assertTrue(act.isEmpty());
}
@Test
void checkGetAnnotationReturnsExistingAnnotation() throws ODataJPAModelException {
createAnnotations();
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final JPAEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.getAnnotation("Capabilities", "FilterRestrictions");
assertNotNull(act);
}
@Test
void checkGetAnnotationReturnsNullAliasUnknown() throws ODataJPAModelException {
createAnnotations();
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final JPAEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
assertNull(es.getAnnotation("Capability", "FilterRestrictions"));
}
@Test
void checkGetAnnotationReturnsNullAnnotationUnknown() throws ODataJPAModelException {
createAnnotations();
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final JPAEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
assertNull(es.getAnnotation("Capabilities", "Filter"));
}
@Test
void checkGetAnnotationValueReturnsNullAnnotationUnknown() throws ODataJPAModelException {
createAnnotations();
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final JPAEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
assertNull(es.getAnnotationValue("Capabilities", "Filter", "Filterable"));
}
static Stream<Arguments> expectedSimpleValue() {
return Stream.of(
Arguments.of(Terms.FILTER_RESTRICTIONS, FilterRestrictionsProperties.FILTERABLE, Boolean.class, Boolean.TRUE),
Arguments.of(Terms.UPDATE_RESTRICTIONS, UpdateRestrictionsProperties.UPDATE_METHOD, String.class,
UpdateMethod.PATCH.name()),
Arguments.of(Terms.UPDATE_RESTRICTIONS, UpdateRestrictionsProperties.DESCRIPTION, String.class, "Just to test"),
Arguments.of(Terms.EXPAND_RESTRICTIONS, ExpandRestrictionsProperties.MAX_LEVELS, Integer.class, Integer.valueOf(
2)));
}
@ParameterizedTest
@MethodSource("expectedSimpleValue")
void checkGetAnnotationValueSimpleProperty(final TermAccess term, final PropertyAccess propertyName,
final Class<?> type, final Object expectedValue) throws ODataJPAModelException {
createAnnotations();
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final JPAEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.getAnnotationValue("Capabilities", term.term(), propertyName.property());
assertNotNull(act);
assertTrue(type.isAssignableFrom(act.getClass()));
assertEquals(expectedValue, act);
assertEquals(expectedValue, es.getAnnotationValue("Capabilities", term.term(), propertyName.property(), type));
assertEquals(expectedValue, es.getAnnotationValue(Aliases.CAPABILITIES, term, propertyName, type));
}
static Stream<Arguments> expectedCollectionValue() {
return Stream.of(
Arguments.of(Terms.FILTER_RESTRICTIONS, FilterRestrictionsProperties.REQUIRED_PROPERTIES, Arrays.asList(
"ParentCodeID", "ParentDivisionCode"), false),
Arguments.of(Terms.COUNT_RESTRICTIONS, CountRestrictionsProperties.NON_COUNTABLE_NAVIGATION_PROPERTIES, Arrays
.asList("Children"), true));
}
@ParameterizedTest
@MethodSource("expectedCollectionValue")
void checkGetAnnotationValueCollectionProperty(final TermAccess term, final PropertyAccess propertyName,
final List<String> expectedValues, final boolean isNavigation) throws ODataJPAModelException {
createAnnotations();
final var et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final List<?> exp;
if (isNavigation) {
exp = expectedValues.stream().map(name -> {
try {
return et.getAssociationPath(name);
} catch (final ODataJPAModelException e) {
fail(e);
return null;
}
}).toList();
} else {
exp = expectedValues.stream().map(name -> {
try {
return et.getPath(name);
} catch (final ODataJPAModelException e) {
fail(e);
return null;
}
}).toList();
}
final JPAEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final var act = es.getAnnotationValue("Capabilities", term.term(), propertyName.property());
assertNotNull(act);
assertEquals(exp, act);
}
@Test
void checkAsUserGroupRestrictedUserRestrictsNavigations() throws ODataJPAModelException {
final IntermediateEntityType<Person> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(Person.class), schema);
final IntermediateEntitySet es = new IntermediateEntitySet(nameBuilder, et, annotationInfo);
final IntermediateEntitySet act = es.asUserGroupRestricted(List.of("Company"));
assertEquals(es.getExternalFQN(), act.getExternalFQN());
assertEquals(es.getExternalName(), act.getExternalName());
assertEquals(es.getInternalName(), act.getInternalName());
assertListEquals(es.getEdmItem().getNavigationPropertyBindings(), act.getEdmItem().getNavigationPropertyBindings(),
CsdlNavigationPropertyBinding.class);
final IntermediateEntitySet act2 = es.asUserGroupRestricted(List.of("Person"));
assertEquals(es.getExternalFQN(), act2.getExternalFQN());
assertEquals(es.getExternalName(), act2.getExternalName());
assertEquals(es.getInternalName(), act2.getInternalName());
assertEquals(es.getEdmItem().getNavigationPropertyBindings().size() - 1, act2.getEdmItem()
.getNavigationPropertyBindings().size());
}
private void createAnnotations() {
final AnnotationProvider annotationProvider = new JavaBasedCapabilitiesAnnotationsProvider();
final List<CsdlProperty> propertiesFilter = new ArrayList<>();
final List<CsdlProperty> propertiesExpand = new ArrayList<>();
final List<CsdlProperty> propertiesUpdate = new ArrayList<>();
final List<CsdlProperty> propertiesCount = new ArrayList<>();
final var termFilter = AnnotationTestHelper.addTermToCapabilitiesReferences(references, "FilterRestrictions",
"FilterRestrictionsType", propertiesFilter);
final var termExpand = AnnotationTestHelper.addTermToCapabilitiesReferences(references, "ExpandRestrictions",
"ExpandRestrictionsType", propertiesExpand);
final var termUpdate = AnnotationTestHelper.addTermToCapabilitiesReferences(references, "UpdateRestrictions",
"UpdateRestrictionsType", propertiesUpdate);
final var termCount = AnnotationTestHelper.addTermToCapabilitiesReferences(references, "CountRestrictions",
"CountRestrictionsType", propertiesCount);
propertiesFilter.add(AnnotationTestHelper.createTermProperty("Filterable", "Edm.Boolean"));
propertiesFilter.add(AnnotationTestHelper.createTermCollectionProperty("RequiredProperties", "Edm.PropertyPath"));
propertiesExpand.add(AnnotationTestHelper.createTermProperty("MaxLevels", "Edm.Int32"));
propertiesUpdate.add(AnnotationTestHelper.createTermProperty("UpdateMethod", "Capabilities.HttpMethod"));
propertiesUpdate.add(AnnotationTestHelper.createTermProperty("Description", "Edm.String"));
propertiesCount.add(AnnotationTestHelper.createTermCollectionProperty("NonCountableNavigationProperties",
"Edm.NavigationPropertyPath"));
when(references.convertAlias("Capabilities")).thenReturn("Org.OData.Capabilities.V1");
when(references.getTerms("Capabilities", Applicability.ENTITY_SET))
.thenReturn(Arrays.asList(termFilter, termExpand, termUpdate, termCount));
annotationInfo.getAnnotationProvider().add(annotationProvider);
}
private static class PostProcessor implements JPAEdmMetadataPostProcessor {
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
if (jpaManagedTypeClassName.equals("com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")
&& property.getInternalName().equals("communicationData")) {
property.setIgnore(true);
}
}
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {
// Not needed
}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {
// Not needed
}
@Override
public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {
// Not needed
}
@Override
public void processEntitySet(final IntermediateEntitySetAccess entitySet) {
final var mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false");
final var annotation = new CsdlAnnotation();
annotation.setExpression(mimeType);
annotation.setTerm("Capabilities.TopSupported");
final List<CsdlAnnotation> annotations = new ArrayList<>();
annotations.add(annotation);
entitySet.addAnnotations(annotations);
}
}
@SuppressWarnings("unchecked")
private <T> EntityType<T> getEntityType(final String typeName) {
for (final EntityType<?> entityType : etList) {
if (entityType.getJavaType().getSimpleName().equals(typeName)) {
return (EntityType<T>) entityType;
}
}
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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateVirtualPropertyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateVirtualPropertyTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.ManagedType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored;
class IntermediateVirtualPropertyTest extends TestMappingRoot {
private IntermediateSchema schema;
private IntermediateVirtualProperty cut;
private Attribute<?, ?> jpaAttribute;
private IntermediateAnnotationInformation annotationInfo;
@BeforeEach
void setup() throws ODataJPAModelException {
final Reflections reflections = mock(Reflections.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
schema = new IntermediateSchema(new JPADefaultEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), reflections,
annotationInfo);
jpaAttribute = mock(Attribute.class);
when(jpaAttribute.getJavaMember()).thenReturn(null);
when(jpaAttribute.getName()).thenReturn("DummyName");
when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer<ManagedType<?>>() {
@Override
public ManagedType<?> answer(final InvocationOnMock invocation) throws Throwable {
return getEntityType(DummyToBeIgnored.class);
}
});
cut = new IntermediateVirtualProperty(nameBuilder, jpaAttribute, schema, "TestColumn", Integer.class);
}
@Test
void checkConstructor() {
assertNotNull(cut);
}
@TestFactory
Iterable<DynamicTest> checkReturnsFixValue() {
return Arrays.asList(
dynamicTest("isEnum returns false", () -> assertFalse(cut.isEnum())),
dynamicTest("isEtag returns false", () -> assertFalse(cut.isEtag())),
dynamicTest("isSearchable returns false", () -> assertFalse(cut.isSearchable())),
dynamicTest("isTransient returns false", () -> assertFalse(cut.isTransient())),
dynamicTest("ignore returns true", () -> assertTrue(cut.ignore())),
dynamicTest("isAssociation returns false", () -> assertFalse(cut.isAssociation())),
dynamicTest("isCollection returns false", () -> assertFalse(cut.isCollection())),
dynamicTest("isComplex returns false", () -> assertFalse(cut.isComplex())),
dynamicTest("isKey returns false", () -> assertFalse(cut.isKey())),
dynamicTest("isStream returns false", () -> assertFalse(cut.isStream())),
dynamicTest("isPartOfGroup returns false", () -> assertFalse(cut.isPartOfGroup())));
}
@TestFactory
Iterable<DynamicTest> checkReturnsNull() {
return Arrays.asList(
dynamicTest("determineType returns null", () -> assertNull(cut.determineType())),
dynamicTest("getStructuredType returns null", () -> assertNull(cut.getStructuredType())),
dynamicTest("getDefaultValue returns null", () -> assertNull(cut.getDefaultValue())));
}
@Test
void testGetDbType() {
assertEquals(Integer.class, cut.getDbType());
}
@Test
void testGetType() {
assertEquals(Integer.class, cut.getType());
}
@Test
void testGetJavaType() {
assertEquals(Integer.class, cut.getJavaType());
}
@Test
void testDetermineIsVersion() {
cut.determineIsVersion();
assertFalse(cut.isEtag());
}
@Test
void testType() throws ODataJPAModelException {
cut.checkConsistency();
cut.determineStreamInfo();
cut.determineStructuredType();
assertNull(cut.getStructuredType());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAEdmNameBuilderTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/JPAEdmNameBuilderTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
class JPAEdmNameBuilderTest {
private JPADefaultEdmNameBuilder cut;
@BeforeEach
public void setup() throws ODataJPAModelException {
}
@Test
void CheckBuildContainerNameSimple() {
cut = new JPADefaultEdmNameBuilder("cdw");
assertEquals("CdwContainer", cut.buildContainerName());
}
@Test
void CheckBuildContainerNameComplex() {
cut = new JPADefaultEdmNameBuilder("org.apache.olingo.jpa");
assertEquals("OrgApacheOlingoJpaContainer", cut.buildContainerName());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/CustomJPANameBuilder.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/CustomJPANameBuilder.java | /**
*
*/
package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import java.util.stream.IntStream;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EmbeddableType;
import jakarta.persistence.metamodel.EntityType;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEdmNameBuilder;
/**
* @author Oliver Grande
* Created: 19.09.2019
*
*/
public class CustomJPANameBuilder implements JPAEdmNameBuilder {
@Override
public String buildComplexTypeName(final EmbeddableType<?> jpaEmbeddedType) {
return new StringBuilder("T_").append(jpaEmbeddedType.getJavaType().getSimpleName()).toString();
}
@Override
public String buildContainerName() {
return "service_container";
}
@Override
public String buildEntitySetName(final String entityTypeName) {
return entityTypeName.toUpperCase();
}
@Override
public String buildEntityTypeName(final EntityType<?> jpaEntityType) {
final StringBuilder externalName = new StringBuilder();
final IntStream name = jpaEntityType.getName().chars();
name.forEach(i -> this.appendChar(externalName, i));
externalName.deleteCharAt(0);
return externalName.toString();
}
@Override
public String buildEnumerationTypeName(final Class<? extends Enum<?>> javaEnum) {
return new StringBuilder("E_").append(javaEnum.getSimpleName()).toString();
}
@Override
public String buildNaviPropertyName(final Attribute<?, ?> jpaAttribute) {
return jpaAttribute.getName();
}
@Override
public String buildOperationName(final String internalOperationName) {
return new StringBuilder("O_").append(internalOperationName).toString();
}
@Override
public String buildPropertyName(final String jpaAttributeName) {
return jpaAttributeName;
}
@Override
public String getNamespace() {
return "test";
}
private void appendChar(final StringBuilder builder, final int i) {
if (Character.isUpperCase(i))
builder.append('_').append(Character.toChars(i)[0]);
else
builder.append(Character.toChars(i)[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-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateOperationHelperTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateOperationHelperTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.TestActionCollection;
class IntermediateOperationHelperTest {
static Stream<Arguments> provideIsCollection() {
return Stream.of(
Arguments.of(ArrayList.class, true),
Arguments.of(List.class, true),
Arguments.of(TestActionCollection.class, true),
Arguments.of(Integer.class, false),
Arguments.of(HashMap.class, false),
Arguments.of(IntermediateProperty.class, false));
}
@ParameterizedTest
@MethodSource("provideIsCollection")
void testIsCollection(final Class<?> clazz, final boolean expected) {
assertEquals(expected, IntermediateOperationHelper.isCollection(clazz));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEmbeddedIdPropertyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateEmbeddedIdPropertyTest.java | /**
*
*/
package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.TRANSIENT_KEY_NOT_SUPPORTED;
import static com.sap.olingo.jpa.processor.core.util.Assertions.assertException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import jakarta.persistence.metamodel.Attribute;
import jakarta.persistence.metamodel.EntityType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.processor.core.errormodel.TeamWithTransientEmbeddableKey;
import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription;
/**
* @author Oliver Grande
* Created: 22.03.2020
*
*/
class IntermediateEmbeddedIdPropertyTest extends TestMappingRoot {
private TestHelper helper;
private TestHelper errorHelper;
private JPAEdmNameBuilder nameBuilder;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
errorHelper = new TestHelper(errorEmf.getMetamodel(), ERROR_PUNIT);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
}
@Test
void checkEmbeddedIdCanBeCreated() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(AdministrativeDivisionDescription.class);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(et, "key");
assertNotNull(new IntermediateEmbeddedIdProperty(new JPADefaultEdmNameBuilder(PUNIT_NAME), jpaAttribute,
helper.schema));
}
@Test
void checkEmbeddedIdIsKey() throws ODataJPAModelException {
final EntityType<?> et = helper.getEntityType(AdministrativeDivisionDescription.class);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(et, "key");
final IntermediateEmbeddedIdProperty cut = new IntermediateEmbeddedIdProperty(new JPADefaultEdmNameBuilder(
PUNIT_NAME), jpaAttribute, helper.schema);
assertTrue(cut.isKey());
}
@Test
void checkEmbeddedIdThrowsExceptionIfTransient() {
final EntityType<?> et = errorHelper.getEntityType(TeamWithTransientEmbeddableKey.class);
final Attribute<?, ?> jpaAttribute = helper.getAttribute(et, "key");
assertException(ODataJPAModelException.class,
() -> new IntermediateEmbeddedIdProperty(nameBuilder, jpaAttribute, helper.schema),
TRANSIENT_KEY_NOT_SUPPORTED.getKey());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateFunctionFactoryTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateFunctionFactoryTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.ODataFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneFunction;
import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoFunctions;
class IntermediateFunctionFactoryTest extends TestMappingRoot {
private TestHelper helper;
private Reflections reflections;
private IntermediateFunctionFactory<?> cut;
private Set<Class<? extends ODataFunction>> javaFunctions;
@BeforeEach
void setUp() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
reflections = mock(Reflections.class);
cut = new IntermediateFunctionFactory<>();
javaFunctions = new HashSet<>();
when(reflections.getSubTypesOf(ODataFunction.class)).thenReturn(javaFunctions);
}
@Test
void checkReturnEmptyMapIfReflectionsNull() throws ODataJPAModelException {
final Reflections r = null;
assertNotNull(cut.create(new JPADefaultEdmNameBuilder(PUNIT_NAME), r, helper.schema));
}
@Test
void checkReturnEmptyMapIfNoJavaFunctionsFound() throws ODataJPAModelException {
assertNotNull(cut.create(new JPADefaultEdmNameBuilder(PUNIT_NAME), reflections, helper.schema));
}
@Test
void checkReturnMapWithOneIfOneJavaFunctionsFound() throws ODataJPAModelException {
javaFunctions.add(ExampleJavaOneFunction.class);
final Map<? extends String, ? extends IntermediateFunction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(1, act.size());
}
@Test
void checkReturnMapWithTwoIfTwoJavaFunctionsFound() throws ODataJPAModelException {
javaFunctions.add(ExampleJavaTwoFunctions.class);
final Map<? extends String, ? extends IntermediateFunction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(2, act.size());
}
@Test
void checkReturnMapWithWithJavaFunctionsFromTwoClassesFound() throws ODataJPAModelException {
javaFunctions.add(ExampleJavaOneFunction.class);
javaFunctions.add(ExampleJavaTwoFunctions.class);
final Map<? extends String, ? extends IntermediateFunction> act = cut.create(new JPADefaultEdmNameBuilder(
PUNIT_NAME), reflections, helper.schema);
assertEquals(3, act.size());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateSingletonTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateSingletonTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static com.sap.olingo.jpa.processor.core.util.Assertions.assertListEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Entity;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlNavigationPropertyBinding;
import org.apache.olingo.commons.api.edm.provider.CsdlSingleton;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEntityType;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.AnnotationProvider;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPASingleton;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateSingletonAccess;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.AnnotationsParent;
import com.sap.olingo.jpa.processor.core.testmodel.AnnotationsSingleton;
import com.sap.olingo.jpa.processor.core.testmodel.CurrentUser;
import com.sap.olingo.jpa.processor.core.testmodel.Singleton;
class IntermediateSingletonTest extends TestMappingRoot {
private IntermediateSchema schema;
private JPADefaultEdmNameBuilder nameBuilder;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateReferences references;
@BeforeEach
void setup() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
final Reflections reflections = mock(Reflections.class);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class)));
references = mock(IntermediateReferences.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>(), references);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
schema = new IntermediateSchema(nameBuilder, emf.getMetamodel(), reflections, annotationInfo);
}
@Test
void checkNewSingleton() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
assertNotNull(singleton);
}
@Test
void checkGetInternalName() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
assertNotNull(singleton.getInternalName());
}
@Test
void checkGetExternalName() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
assertNotNull(singleton.getExternalName());
assertEquals("Singleton", singleton.getExternalName());
}
@Test
void checkGetExternalFQN() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
assertNotNull(singleton.getExternalFQN());
assertEquals(PUNIT_NAME, singleton.getExternalFQN().getNamespace());
assertEquals("Singleton", singleton.getExternalFQN().getName());
}
@Test
void checkGetEdmItem() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final CsdlSingleton item = singleton.getEdmItem();
assertNotNull(item);
}
@Test
void checkGetEdmItemValues() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final CsdlSingleton item = singleton.getEdmItem();
assertEquals("Singleton", item.getName());
assertEquals(PUNIT_NAME + ".Singleton", item.getType());
assertEquals(1, et.getEdmItem().getNavigationProperties().size());
assertEquals(0, item.getNavigationPropertyBindings().size());
}
@Test
void checkAnnotationSet() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new PostProcessor());
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final CsdlSingleton item = singleton.getEdmItem();
final List<CsdlAnnotation> act = item.getAnnotations();
assertEquals(1, act.size());
assertEquals("Capabilities.TopSupported", act.get(0).getTerm());
}
@Test
void checkEntityTypeOfSingletonOnly() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new PostProcessor());
final IntermediateEntityType<CurrentUser> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(CurrentUser.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final CsdlSingleton item = singleton.getEdmItem();
assertEquals(PUNIT_NAME + ".Person", item.getType());
}
@Test
void checkJavaAnnotationsOneAnnotation() {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final Map<String, Annotation> act = et.javaAnnotations(EdmEntityType.class.getPackage().getName());
assertEquals(1, act.size());
assertNotNull(act.get("EdmEntityType"));
}
@Test
void checkJavaAnnotationsTwoAnnotations() {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final Map<String, Annotation> act = et.javaAnnotations(Entity.class.getPackage().getName());
assertEquals(2, act.size());
assertNotNull(act.get("Table"));
assertNotNull(act.get("Entity"));
}
@Test
void checkJavaAnnotationsNoAnnotations() {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final Map<String, Annotation> act = et.javaAnnotations(Test.class.getPackage().toString());
assertTrue(act.isEmpty());
}
@Test
void checkGetAnnotationReturnsExistingAnnotation() throws ODataJPAModelException {
createAnnotation();
final IntermediateEntityType<AnnotationsSingleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsSingleton.class), schema);
final JPASingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final CsdlAnnotation act = singleton.getAnnotation("Capabilities", "CountRestrictions");
assertNotNull(act);
}
@Test
void checkGetAnnotationReturnsNullAnnotationUnknown() throws ODataJPAModelException {
createAnnotation();
final IntermediateEntityType<AnnotationsParent> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(AnnotationsParent.class), schema);
final JPASingleton es = new IntermediateSingleton(nameBuilder, et, annotationInfo);
assertNull(es.getAnnotation("Capabilities", "Filter"));
}
@Test
void checkAsUserGroupRestrictedUserRestrictsNavigations() throws ODataJPAModelException {
final IntermediateEntityType<CurrentUser> et = new IntermediateEntityType<>(
new JPADefaultEdmNameBuilder(PUNIT_NAME), getEntityType(CurrentUser.class), schema);
final var singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final IntermediateSingleton act = singleton.asUserGroupRestricted(List.of("Company"));
assertEquals(singleton.getExternalFQN(), act.getExternalFQN());
assertEquals(singleton.getExternalName(), act.getExternalName());
assertEquals(singleton.getInternalName(), act.getInternalName());
assertListEquals(singleton.getEdmItem().getNavigationPropertyBindings(), act.getEdmItem()
.getNavigationPropertyBindings(),
CsdlNavigationPropertyBinding.class);
final IntermediateSingleton act2 = singleton.asUserGroupRestricted(List.of("Person"));
assertEquals(singleton.getExternalFQN(), act2.getExternalFQN());
assertEquals(singleton.getExternalName(), act2.getExternalName());
assertEquals(singleton.getInternalName(), act2.getInternalName());
assertEquals(singleton.getEdmItem().getNavigationPropertyBindings().size() - 1, act2.getEdmItem()
.getNavigationPropertyBindings().size());
}
private void createAnnotation() {
final AnnotationProvider annotationProvider = mock(AnnotationProvider.class);
final List<CsdlAnnotation> annotations = new ArrayList<>();
final CsdlAnnotation annotation = mock(CsdlAnnotation.class);
annotations.add(annotation);
when(references.convertAlias("Capabilities")).thenReturn("Org.OData.Capabilities.V1");
when(annotation.getTerm()).thenReturn("Org.OData.Capabilities.V1.CountRestrictions");
annotationInfo.getAnnotationProvider().add(annotationProvider);
when(annotationProvider.getAnnotations(eq(Applicability.SINGLETON), any(), any()))
.thenReturn(annotations);
}
private static class PostProcessor implements JPAEdmMetadataPostProcessor {
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
if (jpaManagedTypeClassName.equals("com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")
&& property.getInternalName().equals("communicationData")) {
property.setIgnore(true);
}
}
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {
// Not needed
}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {
// Not needed
}
@Override
public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {
// Not needed
}
@Override
public void processSingleton(final IntermediateSingletonAccess singleton) {
final CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false");
final CsdlAnnotation annotation = new CsdlAnnotation();
annotation.setExpression(mimeType);
annotation.setTerm("Capabilities.TopSupported");
final List<CsdlAnnotation> annotations = new ArrayList<>();
annotations.add(annotation);
singleton.addAnnotations(annotations);
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateCollectionPropertyTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateCollectionPropertyTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.metamodel.Attribute.PersistentAttributeType;
import jakarta.persistence.metamodel.ManagedType;
import jakarta.persistence.metamodel.PluralAttribute;
import jakarta.persistence.metamodel.PluralAttribute.CollectionType;
import jakarta.persistence.metamodel.Type.PersistenceType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
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.JPAPath;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.CollectionFirstLevelComplex;
import com.sap.olingo.jpa.processor.core.testmodel.CollectionSecondLevelComplex;
import com.sap.olingo.jpa.processor.core.testmodel.CollectionWithTwoKey;
import com.sap.olingo.jpa.processor.core.testmodel.ComplexWithTransientComplexCollection;
import com.sap.olingo.jpa.processor.core.testmodel.Organization;
import com.sap.olingo.jpa.processor.core.testmodel.Person;
class IntermediateCollectionPropertyTest extends TestMappingRoot {
private IntermediateCollectionProperty<?> cut;
private TestHelper helper;
private JPAEdmMetadataPostProcessor processor;
private JPADefaultEdmNameBuilder nameBuilder;
private ManagedType<?> managedType;
private IntermediateSchema schema;
private IntermediateAnnotationInformation annotationInfo;
@BeforeEach
void setup() throws ODataJPAModelException {
helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME);
processor = mock(JPAEdmMetadataPostProcessor.class);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
managedType = mock(ManagedType.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>());
schema = new IntermediateSchema(nameBuilder, emf.getMetamodel(), mock(Reflections.class), annotationInfo);
}
@SuppressWarnings("unchecked")
@Test
void checkSimpleCollectionPropertyType() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = mock(PluralAttribute.class);
when(jpaAttribute.getName()).thenReturn("Text");
@SuppressWarnings("rawtypes")
final jakarta.persistence.metamodel.Type type = mock(jakarta.persistence.metamodel.Type.class);
when(type.getPersistenceType()).thenReturn(PersistenceType.BASIC);
when(type.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return String.class;
}
});
when(jpaAttribute.getElementType()).thenReturn(type);
when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer<ManagedType<?>>() {
@Override
public ManagedType<?> answer(final InvocationOnMock invocation) throws Throwable {
return managedType;
}
});
when(managedType.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return Person.class;
}
});
when(jpaAttribute.getJavaType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(final InvocationOnMock invocation) throws Throwable {
return List.class;
}
});
cut = new IntermediateCollectionProperty<>(nameBuilder, jpaAttribute, helper.schema, helper.schema.getEntityType(
Organization.class));
assertEquals("Edm.String", cut.getEdmItem().getType());
assertEquals(String.class, cut.getType());
}
@Test
void checkGetPropertyComplexType() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertEquals(PUNIT_NAME + ".InhouseAddress", property.getEdmItem().getType());
}
@Test
void checkGetPropertyNestedComplexType() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
CollectionWithTwoKey.class), "nested");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(CollectionWithTwoKey.class));
assertNotNull(property.asAssociation().getTargetType());
}
@Test
void checkGetPropertyIgnoreFalse() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertFalse(property.ignore());
}
@Test
void checkGetPropertyDBFieldName() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Organization.class), "comment");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class));
assertEquals("\"Text\"", property.getDBFieldName());
}
@Test
void checkPostProcessorCalled() throws ODataJPAModelException {
IntermediateSimpleProperty.setPostProcessor(processor);
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Organization.class), "comment");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class));
property.getEdmItem();
verify(processor, atLeastOnce()).processProperty(property, ORG_CANONICAL_NAME);
}
@Test
void checkGetPropertyReturnsAnnotation() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
final List<CsdlAnnotation> annotations = property.getEdmItem().getAnnotations();
assertEquals(1, property.getEdmItem().getAnnotations().size());
assertTrue(annotations.get(0).getExpression().isConstant());
}
@Test
void checkGetDeepComplexPropertyReturnsExternalName() throws ODataJPAModelException {
final IntermediateStructuredType<CollectionSecondLevelComplex> st = new IntermediateComplexType<>(nameBuilder,
helper.getComplexType("CollectionSecondLevelComplex"), helper.schema);
for (final JPACollectionAttribute collection : st.getDeclaredCollectionAttributes()) {
if (collection.getInternalName().equals("comment")) {
assertEquals("Comment", collection.asAssociation().getAlias());
assertEquals(collection.asAssociation(), ((JPAAssociationAttribute) collection).getPath());
}
}
final IntermediateStructuredType<CollectionFirstLevelComplex> stst = new IntermediateComplexType<>(nameBuilder,
helper.getComplexType("CollectionFirstLevelComplex"), helper.schema);
for (final JPAPath collection : stst.getCollectionAttributesPath()) {
if (collection.getLeaf().getInternalName().equals("comment")) {
assertEquals("SecondLevel/Comment", collection.getAlias());
}
}
}
@Test
void checkAnnotations() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
cut = new IntermediateCollectionProperty<>(new JPADefaultEdmNameBuilder(PUNIT_NAME),
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
final List<CsdlAnnotation> annotations = cut.getEdmItem().getAnnotations();
assertEquals(1, annotations.size());
assertEquals("Core.Description", annotations.get(0).getTerm());
assertEquals(ConstantExpressionType.String, annotations.get(0).getExpression().asConstant().getType());
assertEquals("Address for inhouse Mail", annotations.get(0).getExpression().asConstant().getValue());
assertEquals("Address", annotations.get(0).getQualifier());
}
@Test
void checkIsTransientOfPrimitiveReturnsTrue() throws ODataJPAModelException, NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = new IntermediateStructuredType.TransientPluralAttribute<>(
helper.getEmbeddableType(CollectionFirstLevelComplex.class),
CollectionFirstLevelComplex.class.getDeclaredField("transientCollection"),
schema);
cut = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getStructuredType(CollectionFirstLevelComplex.class));
assertTrue(cut.isTransient());
assertEquals("Edm.String", cut.getEdmItem().getType());
}
@Test
void checkIsTransientOfComplexReturnsTrue() throws ODataJPAModelException, NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = createTransientPluralAttribute();
cut = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getStructuredType(ComplexWithTransientComplexCollection.class));
assertTrue(cut.isTransient());
assertEquals("com.sap.olingo.jpa.InhouseAddress", cut.getEdmItem().getType());
}
@Test
void checkTransientCollectionType() throws NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = createTransientPluralAttribute();
assertEquals(CollectionType.LIST, jpaAttribute.getCollectionType());
}
@Test
void checkTransientBindableTypeNull() throws NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = createTransientPluralAttribute();
assertNull(jpaAttribute.getBindableType());
}
@Test
void checkTransientBindableJavaTypeNull() throws NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = createTransientPluralAttribute();
assertNull(jpaAttribute.getBindableJavaType());
}
@Test
void checkTransientPersistentAttributeType() throws NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = createTransientPluralAttribute();
assertEquals(PersistentAttributeType.ELEMENT_COLLECTION, jpaAttribute.getPersistentAttributeType());
}
@Test
void checkTransientIsCollectionTrue() throws NoSuchFieldException,
SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = createTransientPluralAttribute();
assertTrue(jpaAttribute.isCollection());
}
@Test
void checkGetPartnerReturnsNull() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertNull(property.getPartner());
}
@Test
void checkIsAssociationFalse() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertFalse(property.isAssociation());
}
@Test
void checkIsSearchableFalse() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertFalse(property.isSearchable());
}
@Test
void checkIsEtagFalse() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertFalse(property.isEtag());
}
@Test
void checkGetTargetEntity() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertNotNull(property.getTargetEntity());
}
@Test
void checkGetTargetAttributeOfSimpleNotNull() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Organization.class), "comment");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class));
final JPAAttribute act = property.getTargetAttribute();
assertNotNull(act);
assertEquals(EdmPrimitiveType.EDM_NAMESPACE + "." + EdmPrimitiveTypeKind.String,
((CsdlProperty) act.getProperty()).getType());
}
@Test
void checkGetTargetAttributeOfComplexNull() throws ODataJPAModelException, SecurityException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertNull(property.getTargetAttribute());
}
@Test
void checkGetJoinTableNotNull() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
assertNotNull(property.getJoinTable());
assertEquals("\"OLINGO\".\"InhouseAddress\"", property.getJoinTable().getTableName());
}
@Test
void checkGetJoinTableLeftColumns() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
final List<JPAPath> act = property.getJoinTable().getLeftColumnsList();
assertNotNull(act);
assertFalse(act.isEmpty());
assertEquals("\"ID\"", act.get(0).getDBFieldName());
}
@Test
void checkGetJoinTableRightColumns() throws ODataJPAModelException {
final PluralAttribute<?, ?, ?> jpaAttribute = helper.getCollectionAttribute(helper.getEntityType(
Person.class), "inhouseAddress");
final IntermediateCollectionProperty<?> property = new IntermediateCollectionProperty<>(nameBuilder,
jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class));
final List<JPAPath> act = property.getJoinTable().getRightColumnsList();
assertNotNull(act);
assertFalse(act.isEmpty());
assertEquals("\"ParentID\"", act.get(0).getDBFieldName());
}
private PluralAttribute<?, ?, ?> createTransientPluralAttribute() throws NoSuchFieldException {
return new IntermediateStructuredType.TransientPluralAttribute<>(
helper.getEmbeddableType(ComplexWithTransientComplexCollection.class),
ComplexWithTransientComplexCollection.class.getDeclaredField("transientCollection"),
schema);
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateReferencesTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateReferencesTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.olingo.commons.api.edm.FullQualifiedName;
import org.apache.olingo.commons.api.edm.provider.CsdlNamed;
import org.apache.olingo.commons.api.edm.provider.CsdlSchema;
import org.apache.olingo.commons.api.edm.provider.CsdlTerm;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.Applicability;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ODataVocabularyReadException;
import com.sap.olingo.jpa.metadata.core.edm.extension.vocabularies.ReferenceAccess;
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.metadata.core.edm.mapper.extension.IntermediateEntityTypeAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateNavigationPropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediatePropertyAccess;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList;
import com.sap.olingo.jpa.metadata.core.edm.mapper.extension.IntermediateReferenceList.IntermediateReferenceAccess;
class IntermediateReferencesTest extends TestMappingRoot {
private static final String TEST_V1_PATH = "annotations/Org.Olingo.Test.V1.xml";
private static final String MEASURES_V1_PATH = "annotations/Org.OData.Measures.V1.xml";
private static final String CORE_V1_PATH = "annotations/Org.OData.Core.V1.xml";
private static final String TEST_V1_URL =
"http://org.example/odata/odata/v4.0/os/vocabularies/Org.Olingo.Test.V1.xml";
private static final String MEASURES_V1_URL =
"https://oasis-tcs.github.io/odata-vocabularies/vocabularies/Org.OData.Measures.V1.xml";
private static final String CORE_V1_URL =
"https://oasis-tcs.github.io/odata-vocabularies/vocabularies/Org.OData.Core.V1.xml";
private IntermediateReferences cut;
@BeforeEach
void setup() {
cut = new IntermediateReferences();
}
@Disabled("This test may not run because of proxy setting problems!! -> find alternative for Integration tests")
@Test
void checkAddOnlyURI() throws ODataJPAModelException {
final String uri = CORE_V1_URL;
cut.addReference(uri);
final List<EdmxReference> act = cut.getEdmReferences();
assertEquals(1, act.size());
assertEquals(act.get(0).getUri().toString(), uri);
}
@Test
void checkThrowsExceptionOnEmptyPath() {
assertThrows(ODataJPAModelException.class, () -> cut.addReference(CORE_V1_URL, ""));
}
@Test
void checkAddURIandPath() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final String path = MEASURES_V1_PATH;
cut.addReference(uri, path);
final List<EdmxReference> act = cut.getEdmReferences();
assertEquals(1, act.size());
assertEquals(uri, act.get(0).getUri().toString());
assertEquals(path, ((IntermediateReferenceList.IntermediateReferenceAccess) cut.references.get(0)).getPath());
assertEquals(uri, ((IntermediateReferenceList.IntermediateReferenceAccess) cut.references.get(0)).getURI()
.toString());
}
@Test
void checkConvertedToCsdlContainsInclude() throws ODataJPAModelException {
JPAServiceDocument serviceDocument;
serviceDocument = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), new PostProcessor(), null,
Collections.emptyList());
assertEquals(1, serviceDocument.getReferences().size());
final EdmxReference ref = serviceDocument.getReferences().get(0);
assertEquals(1, ref.getIncludes().size());
}
@Test
void checkConvertedToCsdlContainsIncludeAnnotation() throws ODataJPAModelException {
JPAServiceDocument serviceDocument;
serviceDocument = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), new PostProcessor(), null,
Collections.emptyList());
assertEquals(1, serviceDocument.getReferences().size());
final EdmxReference ref = serviceDocument.getReferences().get(0);
assertEquals(1, ref.getIncludeAnnotations().size());
}
@Test
void checkGetOneSchema() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Measures.V1", "");
assertEquals(1, cut.getSchemas().size());
}
@Test
void checkGetTwoSchemas() throws ODataJPAModelException {
final String uri = TEST_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, TEST_V1_PATH);
ref.addInclude("Org.Olingo.Test.V1.xml", "");
assertEquals(2, cut.getSchemas().size());
}
@Test
void checkGetComplexType() throws ODataJPAModelException {
final String uri = TEST_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, TEST_V1_PATH);
ref.addInclude("Org.Olingo.Test.V1.xml", "");
for (final CsdlSchema schema : cut.getSchemas())
if (schema.getNamespace().equals("Org.OData.Capabilities.V1")) {
assertNotNull(schema.getComplexType("UpdateRestrictionsType"));
return;
}
fail();
}
@Test
void checkGetTermByNamespace() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Measures.V1", "");
final FullQualifiedName fqn = new FullQualifiedName("Org.OData.Measures.V1", "ISOCurrency");
assertNotNull(cut.getTerm(fqn));
}
@Test
void checkGetTermByAlias() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Measures.V1", "Measures");
final FullQualifiedName fqn = new FullQualifiedName("Measures", "ISOCurrency");
assertNotNull(cut.getTerm(fqn));
}
@Test
void checkReturnEmptyOptionalUnknownTerm() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Measures.V1", "Measures");
final FullQualifiedName fqn = new FullQualifiedName("Measures", "Dummy");
assertFalse(cut.getTerm(fqn).isPresent());
}
@Test
void checkReturnEmptyOptionalOnUnknownNamespace() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Measures.V1", "Measures");
final FullQualifiedName fqn = new FullQualifiedName("Dummy", "ISOCurrency");
assertFalse(cut.getTerm(fqn).isPresent());
}
@Test
void checkAddIncludeWithoutNameSpace() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Org.OData.Core.V1");
assertEquals(1, cut.aliasDirectory.size());
}
@Test
void checkAddIncludeWithNameSpace() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
ref.addInclude("Org.OData.Org.OData.Core.V1", "Core");
assertEquals(2, cut.aliasDirectory.size());
}
@Test
void checkThrowsExceptionOnNullTermNamespace() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
assertThrows(ODataJPAModelException.class, () -> ref.addIncludeAnnotation(null));
}
@Test
void checkThrowsExceptionOnEmptyTermNamespace() throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess ref = cut.addReference(uri, MEASURES_V1_PATH);
assertThrows(ODataJPAModelException.class, () -> ref.addIncludeAnnotation(""));
}
@Test
void checkGetTerms() throws ODataJPAModelException {
final IntermediateReferenceAccess ref = cut.addReference(CORE_V1_URL, CORE_V1_PATH);
ref.addInclude("Org.OData.Core.V1", "Core");
final List<CsdlTerm> act = cut.getTerms("Core", Applicability.ENTITY_SET);
assertNotNull(act);
assertEquals(6, act.size());
assertTrue(act.stream().filter(t -> t.getName().equals("ResourcePath")).findFirst().isPresent());
assertTrue(act.stream().filter(t -> t.getName().equals("OptimisticConcurrency")).findFirst().isPresent());
}
private static Stream<Arguments> getTypeFqn() {
return Stream.of(
Arguments.of(new FullQualifiedName("Org.OData.Core.V1", "RevisionType"), "Complex type via namespace"),
Arguments.of(new FullQualifiedName("Core", "RevisionType"), "Complex type via alice"),
Arguments.of(new FullQualifiedName("Org.OData.Core.V1", "Tag"), "Simple type via namespace"),
Arguments.of(new FullQualifiedName("Core", "Tag"), "Simple type via alice"),
Arguments.of(new FullQualifiedName("Org.OData.Core.V1", "Permission"), "Simple type via namespace"),
Arguments.of(new FullQualifiedName("Core", "Permission"), "Simple type via alice"),
Arguments.of(new FullQualifiedName("Org.OData.Core.V1", "RevisionKind"), "Enumeration type via namespace"),
Arguments.of(new FullQualifiedName("Core", "RevisionKind"), "Enumeration type via alice"));
}
@ParameterizedTest
@MethodSource("getTypeFqn")
void checkGetType(final FullQualifiedName fqn, final String testDescription)
throws ODataJPAModelException {
cut.addReference(CORE_V1_URL, CORE_V1_PATH);
final Optional<CsdlNamed> act = cut.getType(fqn);
assertNotNull(act);
assertTrue(act.isPresent(), testDescription);
}
@Test
void checkAddReferenceWithURI() throws URISyntaxException, ODataVocabularyReadException {
final URI uri = new URI(CORE_V1_URL);
final ReferenceAccess act = cut.addReference(uri, CORE_V1_PATH);
assertNotNull(act);
}
@Test
void checkAddReferenceWithURIRethrowsException() throws URISyntaxException {
final URI uri = new URI(CORE_V1_URL);
final ODataVocabularyReadException act = assertThrows(ODataVocabularyReadException.class, () -> cut.addReference(
uri, "Test"));
assertNotNull(act.getCause());
}
class PostProcessor implements JPAEdmMetadataPostProcessor {
@Override
public void processNavigationProperty(final IntermediateNavigationPropertyAccess property,
final String jpaManagedTypeClassName) {
// Not needed
}
@Override
public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) {
// Not needed
}
@Override
public void processEntityType(final IntermediateEntityTypeAccess entity) {
// Not needed
}
@Override
public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {
final String uri = MEASURES_V1_URL;
final IntermediateReferenceAccess reference = references.addReference(uri,
MEASURES_V1_PATH);
reference.addInclude("Org.OData.Core.V1", "Core");
reference.addIncludeAnnotation("Org.OData.Core.V1");
}
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TimeInstantLongConverterTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TimeInstantLongConverterTest.java | /**
*
*/
package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.sap.olingo.jpa.metadata.converter.TimeInstantLongConverter;
/**
*
* @author Oliver Grande
* @since 1.0.0-RC
*/
class TimeInstantLongConverterTest {
private static final String FIVE_DAYS_LATER = "1970-01-06T00:00:00Z";
private static final long FIVE_DAYS = 5 * 24 * 60 * 60 * 1000;
private TimeInstantLongConverter cut;
@BeforeEach
void setup() {
cut = new TimeInstantLongConverter();
}
@Test
void checkConvertToDatabaseColumnReturnNullOnNull() {
assertNull(cut.convertToDatabaseColumn(null));
}
@Test
void checkConvertToEntityAttributeReturnNullOnNull() {
assertNull(cut.convertToEntityAttribute(null));
}
@Test
void checkConvertToDatabaseColumnReturnConvertedOnNonNull() {
final Instant time = Instant.parse(FIVE_DAYS_LATER);
final Long act = (Long) cut.convertToDatabaseColumn(time);
assertEquals(FIVE_DAYS, act);
}
@Test
void checkConvertToEntityAttributeReturnConvertedOnNonNull() {
final Instant act = cut.convertToEntityAttribute(FIVE_DAYS);
assertEquals(FIVE_DAYS_LATER, act.toString());
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateTopLevelEntityTest.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/IntermediateTopLevelEntityTest.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import org.apache.olingo.commons.api.edm.provider.annotation.CsdlDynamicExpression;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.reflections8.Reflections;
import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration;
import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import com.sap.olingo.jpa.processor.core.testmodel.ABCClassification;
import com.sap.olingo.jpa.processor.core.testmodel.Singleton;
class IntermediateTopLevelEntityTest extends TestMappingRoot {
private IntermediateSchema schema;
private JPADefaultEdmNameBuilder nameBuilder;
private IntermediateAnnotationInformation annotationInfo;
private IntermediateReferences references;
@BeforeEach
void setup() throws ODataJPAModelException {
IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor());
final Reflections reflections = mock(Reflections.class);
when(reflections.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(
ABCClassification.class)));
references = mock(IntermediateReferences.class);
annotationInfo = new IntermediateAnnotationInformation(new ArrayList<>(), references);
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
schema = new IntermediateSchema(nameBuilder, emf.getMetamodel(), reflections, annotationInfo);
}
@Test
void checkQueryExtensionProviderPresent() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
assertFalse(singleton.getQueryExtension().isPresent());
}
@Test
void checkGetAnnotationDynamicValueReturnsNull() throws ODataJPAModelException {
final IntermediateEntityType<Singleton> et = new IntermediateEntityType<>(new JPADefaultEdmNameBuilder(
PUNIT_NAME), getEntityType(Singleton.class), schema);
final IntermediateSingleton singleton = new IntermediateSingleton(nameBuilder, et, annotationInfo);
final var expression = mock(CsdlDynamicExpression.class);
assertNull(singleton.getAnnotationDynamicValue("Name", expression));
}
}
| java | Apache-2.0 | c6fddac331f51f37fd9e4b46aa6bf7ab256c386b | 2026-01-05T02:41:58.937563Z | false |
SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4/blob/c6fddac331f51f37fd9e4b46aa6bf7ab256c386b/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java | jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java | package com.sap.olingo.jpa.metadata.core.edm.mapper.impl;
import java.util.Set;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.metamodel.EntityType;
import org.junit.jupiter.api.BeforeAll;
import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory;
import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper;
public class TestMappingRoot {
protected static final String PUNIT_NAME = "com.sap.olingo.jpa";
protected static final String ERROR_PUNIT = "error";
protected static EntityManagerFactory emf;
protected static EntityManagerFactory errorEmf;
protected static JPADefaultEdmNameBuilder nameBuilder;
protected static JPADefaultEdmNameBuilder errorNameBuilder;
protected static Set<EntityType<?>> etList;
public static final String BUPA_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner";
public static final String ORG_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.Organization";
public static final String ADDR_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData";
public static final String COMM_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.CommunicationData";
public static final String ADMIN_CANONICAL_NAME =
"com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision";
@BeforeAll
static void setupClass() {
emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, DataSourceHelper.createDataSource(
DataSourceHelper.DB_HSQLDB));
errorEmf = JPAEntityManagerFactory.getEntityManagerFactory(ERROR_PUNIT, DataSourceHelper.createDataSource(
DataSourceHelper.DB_HSQLDB));
nameBuilder = new JPADefaultEdmNameBuilder(PUNIT_NAME);
errorNameBuilder = new JPADefaultEdmNameBuilder(ERROR_PUNIT);
etList = emf.getMetamodel().getEntities();
}
@SuppressWarnings("unchecked")
<T> EntityType<T> getEntityType(final Class<T> type) {
for (final EntityType<?> entityType : etList) {
if (entityType.getJavaType().equals(type)) {
return (EntityType<T>) entityType;
}
}
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.