From d1c16a728dd30331acc38eb3f548069d58d716db Mon Sep 17 00:00:00 2001 From: thiagotognoli Date: Fri, 1 Aug 2025 22:55:48 -0300 Subject: [PATCH 1/3] jee9 --- README.md | 5 +- odata-core/.classpath | 24 + odata-core/pom.xml | 10 +- .../odata4j/consumer/AbstractODataClient.java | 16 +- .../consumer/ConsumerFunctionCallRequest.java | 8 +- .../consumer/ODataClientBatchResponse.java | 31 + .../odata4j/consumer/ODataClientResponse.java | 2 +- .../behaviors/AzureTableBehavior.java | 2 +- .../java/org/odata4j/core/ODataConstants.java | 17 +- .../exceptions/BadRequestException.java | 4 +- .../odata4j/exceptions/ExceptionFactory.java | 24 +- .../exceptions/ForbiddenException.java | 4 +- .../exceptions/MethodNotAllowedException.java | 4 +- .../exceptions/NotAcceptableException.java | 4 +- .../exceptions/NotAuthorizedException.java | 4 +- .../odata4j/exceptions/NotFoundException.java | 4 +- .../exceptions/NotImplementedException.java | 4 +- .../exceptions/ODataProducerException.java | 61 +- .../exceptions/ODataProducerExceptions.java | 32 +- .../exceptions/ServerErrorException.java | 4 +- .../UnsupportedMediaTypeException.java | 4 +- .../odata4j/format/FormatParserFactory.java | 11 +- .../java/org/odata4j/format/FormatType.java | 2 +- .../java/org/odata4j/format/FormatWriter.java | 9 +- .../odata4j/format/FormatWriterFactory.java | 20 +- .../json/JsonCollectionFormatWriter.java | 5 +- .../json/JsonComplexObjectFormatWriter.java | 5 +- .../format/json/JsonEntryFormatWriter.java | 2 +- .../format/json/JsonErrorFormatWriter.java | 2 +- .../format/json/JsonFeedFormatParser.java | 2 +- .../format/json/JsonFeedFormatWriter.java | 83 +-- .../odata4j/format/json/JsonFormatWriter.java | 73 ++- .../format/json/JsonPropertyFormatWriter.java | 16 +- .../format/json/JsonRawFormatWriter.java | 160 ++--- .../json/JsonRequestEntryFormatWriter.java | 4 +- .../json/JsonServiceDocumentFormatWriter.java | 40 +- .../format/json/JsonSimpleFormatWriter.java | 2 +- .../json/JsonSingleLinkFormatWriter.java | 14 +- .../json/JsonSingleLinksFormatWriter.java | 28 +- .../xml/AtomCollectionFormatWriter.java | 2 +- .../format/xml/AtomComplexFormatWriter.java | 2 +- .../format/xml/AtomEntryFormatWriter.java | 5 +- .../format/xml/AtomErrorFormatWriter.java | 2 +- .../format/xml/AtomFeedFormatParser.java | 159 ++--- .../format/xml/AtomFeedFormatWriter.java | 10 +- .../format/xml/AtomRawFormatWriter.java | 158 ++--- .../xml/AtomRequestEntryFormatWriter.java | 2 +- .../xml/AtomServiceDocumentFormatWriter.java | 2 +- .../format/xml/AtomSimpleFormatWriter.java | 2 +- .../xml/AtomSingleLinkFormatWriter.java | 2 +- .../xml/AtomSingleLinksFormatWriter.java | 2 +- .../odata4j/format/xml/XmlFormatWriter.java | 21 +- .../format/xml/XmlPropertyFormatWriter.java | 2 +- .../org/odata4j/internal/InternalUtil.java | 53 +- .../producer/ErrorResponseExtension.java | 29 +- .../producer/ErrorResponseExtensions.java | 14 +- .../odata4j/producer/ODataContextImpl.java | 16 +- .../odata4j/producer/ODataHeadersImpl.java | 4 +- .../odata4j/producer/OMediaLinkExtension.java | 55 +- .../resources/AbstractODataApplication.java | 8 +- .../producer/resources/BaseResource.java | 51 +- .../producer/resources/BatchBodyPart.java | 6 +- .../ClientAccessPolicyXmlResource.java | 6 +- .../resources/CrossDomainXmlResource.java | 6 +- .../DefaultODataProducerProvider.java | 47 +- .../resources/EntitiesRequestResource.java | 159 ++--- .../resources/EntityRequestResource.java | 127 ++-- .../resources/ExceptionMappingProvider.java | 46 +- .../producer/resources/FunctionResource.java | 82 +-- .../odata4j/producer/resources/HeaderMap.java | 96 ++- .../resources/LinksRequestResource.java | 48 +- .../producer/resources/MetadataResource.java | 58 +- .../resources/ODataBatchProvider.java | 22 +- .../resources/OptionsQueryParser.java | 2 +- .../resources/PropertyRequestResource.java | 106 ++-- .../producer/resources/RootApplication.java | 5 +- .../resources/ServiceDocumentResource.java | 24 +- .../resources/ValueRequestResource.java | 30 +- .../odata4j/producer/server/ODataServer.java | 6 +- .../stax2/staximpl/StaxXMLWriter2.java | 3 +- .../odata4j/urlencoder/ConversionUtil.java | 162 +++++ .../unit/expressions/TypeConverterTest.java | 38 +- .../format/AbstractErrorFormatWriterTest.java | 16 +- .../format/xml/AtomFeedFormatWriterTest.java | 15 +- .../producer/ErrorResponseExtensionTest.java | 23 +- pom.xml | 20 +- test-integration/.classpath | 19 + test-integration/pom.xml | 47 +- .../cxf/consumer/CxfClientResponse.java | 2 +- .../examples/cxf/consumer/ODataCxfClient.java | 62 +- .../cxf/consumer/ODataCxfConsumer.java | 33 +- .../cxf/producer/server/ODataCxfServer.java | 17 +- .../consumer/DefaultJerseyClientFactory.java | 22 +- .../jersey/consumer/JerseyClientFactory.java | 9 +- .../jersey/consumer/JerseyClientResponse.java | 8 +- .../jersey/consumer/JerseyClientUtil.java | 100 +-- .../jersey/consumer/ODataJerseyClient.java | 366 ++++++++--- .../jersey/consumer/ODataJerseyConsumer.java | 35 +- .../AllowSelfSignedCertsBehavior.java | 78 --- .../behaviors/JerseyClientBehavior.java | 11 +- .../jersey/internal/StringProvider2.java | 26 +- .../resources/ODataProducerProvider.java | 14 +- .../producer/server/ODataJerseyServer.java | 122 ++-- .../integration/AbstractIntegrationTest.java | 34 +- .../AbstractJettyHttpClientTest.java | 12 +- .../test/integration/AbstractRuntimeTest.java | 48 +- .../test/integration/CxfRuntimeFacade.java | 99 +-- .../test/integration/JerseyRuntimeFacade.java | 110 ++-- .../test/integration/PortConflictTest.java | 39 ++ .../test/integration/RuntimeFacade.java | 14 +- .../consumer/BasicAuthenticationTest.java | 28 +- .../test/integration/consumer/ErrorTest.java | 4 +- .../function/FunctionImportTest.java | 569 ++++++++++-------- .../test/integration/issues/Issue16Test.java | 8 +- .../producer/custom/CustomBaseTest.java | 18 +- .../producer/custom/CustomProducer.java | 56 +- .../producer/custom/CustomTest.java | 29 +- .../AddressBookJettyHttpClientTest.java | 16 +- .../test/integration/server/ContextTest.java | 92 +-- .../test/integration/server/ErrorTest.java | 106 ---- .../server/RequestFilteringTest.java | 24 +- .../test/integration/server/SmokeTest.java | 28 +- 122 files changed, 2784 insertions(+), 2021 deletions(-) create mode 100644 odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java create mode 100644 odata-core/src/main/java/org/odata4j/urlencoder/ConversionUtil.java delete mode 100644 test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/AllowSelfSignedCertsBehavior.java create mode 100644 test-integration/src/test/java/org/odata4j/test/integration/PortConflictTest.java diff --git a/README.md b/README.md index f2a0ac6..102cbda 100644 --- a/README.md +++ b/README.md @@ -6,4 +6,7 @@ OData + Rest + Java ==> shake it ==> o-re-va (that's it, no other meaning behi This is complete fork of OData4J for the use of Teiid, but I guess anybody who wants to implement OData V2 can use it. There is no support JPA or JDBC in this version. I always thought they polluted the OData framework, they do not belong in -the core project. The frameworks needs to be about OData. JPA or JDBC can be additional modules. \ No newline at end of file +the core project. The frameworks needs to be about OData. JPA or JDBC can be additional modules. + +## Install with +$ mvn install -P release \ No newline at end of file diff --git a/odata-core/.classpath b/odata-core/.classpath index eff18de..ebbac42 100644 --- a/odata-core/.classpath +++ b/odata-core/.classpath @@ -17,6 +17,7 @@ + @@ -29,5 +30,28 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/odata-core/pom.xml b/odata-core/pom.xml index 2888ae3..e961125 100644 --- a/odata-core/pom.xml +++ b/odata-core/pom.xml @@ -19,10 +19,10 @@ ${project.version} - org.jboss.spec.javax.ws.rs - jboss-jaxrs-api_2.0_spec - ${jsr311.version} - + jakarta.ws.rs + jakarta.ws.rs-api + ${jakartawsrs.version} + joda-time joda-time @@ -48,7 +48,7 @@ org.mockito - mockito-all + mockito-core ${mockito.version} test diff --git a/odata-core/src/main/java/org/odata4j/consumer/AbstractODataClient.java b/odata-core/src/main/java/org/odata4j/consumer/AbstractODataClient.java index 7183095..2f212d3 100644 --- a/odata-core/src/main/java/org/odata4j/consumer/AbstractODataClient.java +++ b/odata-core/src/main/java/org/odata4j/consumer/AbstractODataClient.java @@ -2,8 +2,8 @@ import java.util.List; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.core4j.Enumerable; import org.odata4j.core.OEntities; @@ -25,7 +25,8 @@ import org.odata4j.stax2.XMLEventReader2; /** - * Useful base class for {@link ODataClient} implementations with common functionality. + * Useful base class for {@link ODataClient} implementations with common + * functionality. */ public abstract class AbstractODataClient implements ODataClient { @@ -48,7 +49,8 @@ public EdmDataServices getMetadata(ODataClientRequest request) throws ODataProdu public Iterable getCollections(ODataClientRequest request) throws ODataProducerException { ODataClientResponse response = doRequest(FormatType.ATOM, request, Status.OK); - Enumerable collections = Enumerable.create(AtomServiceDocumentFormatParser.parseWorkspaces(toXml(response))) + Enumerable collections = Enumerable + .create(AtomServiceDocumentFormatParser.parseWorkspaces(toXml(response))) .selectMany(AtomWorkspaceInfo.GET_COLLECTIONS); response.close(); return collections; @@ -98,7 +100,8 @@ public void updateLink(ODataClientRequest request) throws ODataProducerException doRequest(getFormatType(), request, Status.NO_CONTENT).close(); } - public Entry createRequestEntry(EdmEntitySet entitySet, OEntityKey entityKey, List> props, List links) { + public Entry createRequestEntry(EdmEntitySet entitySet, OEntityKey entityKey, List> props, + List links) { final OEntity entity = entityKey == null ? OEntities.createRequest(entitySet, props, links) : OEntities.create(entitySet, entityKey, props, links); @@ -116,7 +119,8 @@ public OEntity getEntity() { }; } - protected abstract ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, StatusType... expectedResponseStatus) throws ODataProducerException; + protected abstract ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, + StatusType... expectedResponseStatus) throws ODataProducerException; protected abstract XMLEventReader2 toXml(ODataClientResponse response); diff --git a/odata-core/src/main/java/org/odata4j/consumer/ConsumerFunctionCallRequest.java b/odata-core/src/main/java/org/odata4j/consumer/ConsumerFunctionCallRequest.java index 9e6b6ef..07e3a9b 100644 --- a/odata-core/src/main/java/org/odata4j/consumer/ConsumerFunctionCallRequest.java +++ b/odata-core/src/main/java/org/odata4j/consumer/ConsumerFunctionCallRequest.java @@ -10,6 +10,7 @@ import org.core4j.Enumerable; import org.core4j.Func; import org.core4j.ReadOnlyIterator; +import org.core4j.ReadOnlyIterator.IterationResult; import org.joda.time.LocalDateTime; import org.odata4j.core.Guid; import org.odata4j.core.OCollection; @@ -186,10 +187,13 @@ public OFunctionRequest pString(String name, String value) { private OObject doRequest(ODataClientRequest request) throws ODataProducerException { ODataClientResponse response = getClient().callFunction(request); - ODataVersion version = InternalUtil.getDataServiceVersion(response.getHeaders().getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); + ODataVersion version = InternalUtil + .getDataServiceVersion(response.getHeaders().getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); + Class returnTypeClass = function.getReturnType().isSimple() ? OSimpleObject.class + : EdmType.getInstanceType(function.getReturnType()); FormatParser parser = FormatParserFactory.getParser( - function.getReturnType().isSimple() ? OSimpleObject.class : EdmType.getInstanceType(function.getReturnType()), + returnTypeClass, getClient().getFormatType(), new Settings( version, diff --git a/odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java b/odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java new file mode 100644 index 0000000..404c0a1 --- /dev/null +++ b/odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java @@ -0,0 +1,31 @@ +package org.odata4j.consumer; + +/** + * This interface define the result returned from batch request. + * The result depends on request type. + * All the request will return a staus code, but not all requests will return + * entity. + * + * @author Kevin Chen + * + */ +public interface ODataClientBatchResponse extends ODataClientResponse { + /** + * Return the status code of this individual request. + * + * @return the status code. + */ + public int getStatus(); + + /** + * Return the content. The content is based on the request. + * getEntities request ---> Enumerable + * getEntity request ------> T + * createEntity request ----> T + * update/delete request -----> null + * T is the entity type request. + * + * @return the entities. + */ + public Object getEntity(); +} diff --git a/odata-core/src/main/java/org/odata4j/consumer/ODataClientResponse.java b/odata-core/src/main/java/org/odata4j/consumer/ODataClientResponse.java index 464f6fc..c1da8b2 100644 --- a/odata-core/src/main/java/org/odata4j/consumer/ODataClientResponse.java +++ b/odata-core/src/main/java/org/odata4j/consumer/ODataClientResponse.java @@ -1,6 +1,6 @@ package org.odata4j.consumer; -import javax.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.MultivaluedMap; /** * Generic OData http response used by the low-level {@link ODataClient} api. diff --git a/odata-core/src/main/java/org/odata4j/consumer/behaviors/AzureTableBehavior.java b/odata-core/src/main/java/org/odata4j/consumer/behaviors/AzureTableBehavior.java index 932b817..0b9ddc6 100644 --- a/odata-core/src/main/java/org/odata4j/consumer/behaviors/AzureTableBehavior.java +++ b/odata-core/src/main/java/org/odata4j/consumer/behaviors/AzureTableBehavior.java @@ -6,7 +6,7 @@ import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; diff --git a/odata-core/src/main/java/org/odata4j/core/ODataConstants.java b/odata-core/src/main/java/org/odata4j/core/ODataConstants.java index c7cb812..11711b6 100644 --- a/odata-core/src/main/java/org/odata4j/core/ODataConstants.java +++ b/odata-core/src/main/java/org/odata4j/core/ODataConstants.java @@ -1,26 +1,35 @@ package org.odata4j.core; +import org.odata4j.core.ODataConstants.Charsets; + /** * Useful constants. */ public class ODataConstants { - private ODataConstants() {} + private ODataConstants() { + } public static final String TEXT_PLAIN = "text/plain"; public static final String TEXT_PLAIN_CHARSET_UTF8 = TEXT_PLAIN + ";charset=" + Charsets.Lower.UTF_8; public static final String APPLICATION_ATOM_XML = "application/atom+xml"; - public static final String APPLICATION_ATOM_XML_CHARSET_UTF8 = APPLICATION_ATOM_XML + ";charset=" + Charsets.Lower.UTF_8; + public static final String APPLICATION_ATOM_XML_CHARSET_UTF8 = APPLICATION_ATOM_XML + ";charset=" + + Charsets.Lower.UTF_8; public static final String APPLICATION_ATOMSVC_XML = "application/atomsvc+xml"; - public static final String APPLICATION_ATOMSVC_XML_CHARSET_UTF8 = APPLICATION_ATOMSVC_XML + ";charset=" + Charsets.Lower.UTF_8; + public static final String APPLICATION_ATOMSVC_XML_CHARSET_UTF8 = APPLICATION_ATOMSVC_XML + ";charset=" + + Charsets.Lower.UTF_8; + public static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; public static final String APPLICATION_XML = "application/xml"; public static final String APPLICATION_XML_CHARSET_UTF8 = "application/xml;charset=" + Charsets.Lower.UTF_8; public static final String TEXT_JAVASCRIPT_CHARSET_UTF8 = "text/javascript;charset=" + Charsets.Lower.UTF_8; public static final String APPLICATION_JAVASCRIPT = "application/json"; - public static final String APPLICATION_JAVASCRIPT_CHARSET_UTF8 = APPLICATION_JAVASCRIPT + ";charset=" + Charsets.Lower.UTF_8; + public static final String APPLICATION_JAVASCRIPT_CHARSET_UTF8 = APPLICATION_JAVASCRIPT + ";charset=" + + Charsets.Lower.UTF_8; + + public static final String JERSEY_CLIENT_CHUNKED_ENCODING_SIZE = "jersey.config.client.chunkedEncodingSize"; public static final ODataVersion DATA_SERVICE_VERSION = ODataVersion.V1; public static final String DATA_SERVICE_VERSION_HEADER = DATA_SERVICE_VERSION.asString; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/BadRequestException.java b/odata-core/src/main/java/org/odata4j/exceptions/BadRequestException.java index b485928..8be10b5 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/BadRequestException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/BadRequestException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/ExceptionFactory.java b/odata-core/src/main/java/org/odata4j/exceptions/ExceptionFactory.java index 2a65510..66fdb62 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/ExceptionFactory.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/ExceptionFactory.java @@ -3,14 +3,20 @@ import org.odata4j.core.OError; /** - * A factory for instances of a specific sub-class of {@link ODataProducerException}. + * A factory for instances of a specific sub-class of + * {@link ODataProducerException}. * - *

Implementations of this interface are registered to and used by {@link ODataProducerExceptions}. - * When an OData consumer receives an error message returned by an OData producer, the parsed - * {@link OError} is wrapped into an exception and thrown via the consumer API.

+ *

+ * Implementations of this interface are registered to and used by + * {@link ODataProducerExceptions}. + * When an OData consumer receives an error message returned by an OData + * producer, the parsed + * {@link OError} is wrapped into an exception and thrown via the consumer API. + *

* - * @param the concrete sub-class of {@link ODataProducerException} created - * @see ODataProducerExceptions#create(javax.ws.rs.core.Response.StatusType, OError) + * @param the concrete sub-class of {@link ODataProducerException} created + * @see ODataProducerExceptions#create(jakarta.ws.rs.core.Response.StatusType, + * OError) */ public interface ExceptionFactory { @@ -22,9 +28,11 @@ public interface ExceptionFactory { int getStatusCode(); /** - * Creates an instance of a specific sub-class of {@link ODataProducerException}. + * Creates an instance of a specific sub-class of + * {@link ODataProducerException}. * - * @param error the OData error message to be wrapped into the returned exception + * @param error the OData error message to be wrapped into the returned + * exception * @return the exception instance */ T createException(OError error); diff --git a/odata-core/src/main/java/org/odata4j/exceptions/ForbiddenException.java b/odata-core/src/main/java/org/odata4j/exceptions/ForbiddenException.java index e2a42f7..51f96f2 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/ForbiddenException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/ForbiddenException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/MethodNotAllowedException.java b/odata-core/src/main/java/org/odata4j/exceptions/MethodNotAllowedException.java index abe428f..349df94 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/MethodNotAllowedException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/MethodNotAllowedException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status.Family; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/NotAcceptableException.java b/odata-core/src/main/java/org/odata4j/exceptions/NotAcceptableException.java index d561115..89e63a5 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/NotAcceptableException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/NotAcceptableException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/NotAuthorizedException.java b/odata-core/src/main/java/org/odata4j/exceptions/NotAuthorizedException.java index 6abc4dd..49f4c3f 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/NotAuthorizedException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/NotAuthorizedException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/NotFoundException.java b/odata-core/src/main/java/org/odata4j/exceptions/NotFoundException.java index e0c3d8f..d0acce4 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/NotFoundException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/NotFoundException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/NotImplementedException.java b/odata-core/src/main/java/org/odata4j/exceptions/NotImplementedException.java index d4e4c43..3cedeba 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/NotImplementedException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/NotImplementedException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status.Family; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerException.java b/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerException.java index 244e36f..34f392e 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerException.java @@ -3,18 +3,23 @@ import java.io.PrintWriter; import java.io.StringWriter; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; import org.odata4j.core.OErrors; /** - * An OData producer exception with the information described in the OData documentation for - * error conditions. + * An OData producer exception with the information described in the OData + * documentation for + * error + * conditions. * - *

OData producer exceptions can be either created by using one of its sub-classes or by the - * static factory {@link ODataProducerExceptions}.

+ *

+ * OData producer exceptions can be either created by using one of its + * sub-classes or by the + * static factory {@link ODataProducerExceptions}. + *

*/ public abstract class ODataProducerException extends RuntimeException { @@ -23,9 +28,13 @@ public abstract class ODataProducerException extends RuntimeException { private final OError error; /** - * Constructor used by sub-classes to instantiate an exception that is thrown by an OData provider at runtime. + * Constructor used by sub-classes to instantiate an exception that is thrown by + * an OData provider at runtime. * - *

Parameters are delegated to {@link RuntimeException#RuntimeException(String, Throwable)}.

+ *

+ * Parameters are delegated to + * {@link RuntimeException#RuntimeException(String, Throwable)}. + *

*/ protected ODataProducerException(String message, Throwable cause) { super(message, cause); @@ -33,7 +42,8 @@ protected ODataProducerException(String message, Throwable cause) { } /** - * Constructor used by sub-classes to instantiate an exception based on the given OError + * Constructor used by sub-classes to instantiate an exception based on the + * given OError * that has been received and parsed by an OData consumer. */ protected ODataProducerException(OError error) { @@ -42,10 +52,14 @@ protected ODataProducerException(OError error) { } /** - * Returns the code that is put into the OError object created during construction of this exception. + * Returns the code that is put into the OError object created during + * construction of this exception. * - *

The default implementation returns the simple name of the underlying class. Sub-classes can override - * this method and specify a different code.

+ *

+ * The default implementation returns the simple name of the underlying class. + * Sub-classes can override + * this method and specify a different code. + *

* * @return the code * @see OError#getCode() @@ -55,11 +69,16 @@ protected String code() { } /** - * Returns the message that is put into the OError object created during construction of this exception. + * Returns the message that is put into the OError object created during + * construction of this exception. * - *

The default implementation returns the exception's message ({@link RuntimeException#getMessage()}) if set. - * Otherwise the reason phrase of the mapped HTTP status is returned ({@link StatusType#getReasonPhrase()}). - * Sub-classes can override this method and specify a different message.

+ *

+ * The default implementation returns the exception's message + * ({@link RuntimeException#getMessage()}) if set. + * Otherwise the reason phrase of the mapped HTTP status is returned + * ({@link StatusType#getReasonPhrase()}). + * Sub-classes can override this method and specify a different message. + *

* * @return the message * @see OError#getMessage() @@ -73,10 +92,14 @@ protected String message() { } /** - * Returns the inner error that is put into the OError object created during construction of this exception. + * Returns the inner error that is put into the OError object created during + * construction of this exception. * - *

The default implementation returns the exception's stack trace ({@link RuntimeException#printStackTrace(PrintWriter)}). - * Sub-classes can override this method and specify a different inner error.

+ *

+ * The default implementation returns the exception's stack trace + * ({@link RuntimeException#printStackTrace(PrintWriter)}). + * Sub-classes can override this method and specify a different inner error. + *

* * @return the inner error * @see OError#getInnerError() diff --git a/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerExceptions.java b/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerExceptions.java index be816c8..c32dc1d 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerExceptions.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/ODataProducerExceptions.java @@ -3,16 +3,20 @@ import java.util.HashMap; import java.util.Map; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; import org.odata4j.core.Throwables; /** * A static factory to create {@link ODataProducerException} instances. - *

This factory is used after deserialization of error responses retrieved from an OData - * producer; it returns one of the following exceptions based on the HTTP status of the response: - *

  • {@link BadRequestException},
  • + *

    + * This factory is used after deserialization of error responses retrieved from + * an OData + * producer; it returns one of the following exceptions based on the HTTP status + * of the response: + *

      + *
    • {@link BadRequestException},
    • *
    • {@link ForbiddenException},
    • *
    • {@link MethodNotAllowedException},
    • *
    • {@link NotAcceptableException},
    • @@ -20,14 +24,18 @@ *
    • {@link NotFoundException},
    • *
    • {@link NotImplementedException},
    • *
    • {@link ServerErrorException},
    • - *
    • {@link UnsupportedMediaTypeException}
    - * In case the HTTP status cannot be mapped to a specific sub-class, an unspecific ODataProducerException is thrown.

    + *
  • {@link UnsupportedMediaTypeException}
  • + *
+ * In case the HTTP status cannot be mapped to a specific sub-class, an + * unspecific ODataProducerException is thrown. + *

*/ public class ODataProducerExceptions { private static ODataProducerExceptions SINGLETON = new ODataProducerExceptions(); - private ODataProducerExceptions() {} + private ODataProducerExceptions() { + } private Map> exceptionFactories = null; @@ -45,15 +53,17 @@ private void initializeExceptionMap() throws InstantiationException, IllegalAcce add(new UnsupportedMediaTypeException.Factory()); } - private static void ensureThatExceptionFactoryMapIsInitialized() throws InstantiationException, IllegalAccessException { + private static void ensureThatExceptionFactoryMapIsInitialized() + throws InstantiationException, IllegalAccessException { if (SINGLETON.exceptionFactories == null) SINGLETON.initializeExceptionMap(); } /** - * Adds an {@link ExceptionFactory} and thus makes the created exception available (and catchable) for OData consumers. + * Adds an {@link ExceptionFactory} and thus makes the created exception + * available (and catchable) for OData consumers. * - * @param exceptionFactory the exception factory to add + * @param exceptionFactory the exception factory to add */ public static void add(final ExceptionFactory exceptionFactory) { try { @@ -79,7 +89,7 @@ public static void restore() { /** * Creates a new {@link ODataProducerException}. * - * @param status the HTTP status received in conjunction with this error + * @param status the HTTP status received in conjunction with this error * @param error the OData error message returned by the producer * @return an instance of {@link ODataProducerException} */ diff --git a/odata-core/src/main/java/org/odata4j/exceptions/ServerErrorException.java b/odata-core/src/main/java/org/odata4j/exceptions/ServerErrorException.java index 78dad2c..fec5b87 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/ServerErrorException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/ServerErrorException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/exceptions/UnsupportedMediaTypeException.java b/odata-core/src/main/java/org/odata4j/exceptions/UnsupportedMediaTypeException.java index 6d8ccca..43283c3 100644 --- a/odata-core/src/main/java/org/odata4j/exceptions/UnsupportedMediaTypeException.java +++ b/odata-core/src/main/java/org/odata4j/exceptions/UnsupportedMediaTypeException.java @@ -1,7 +1,7 @@ package org.odata4j.exceptions; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/format/FormatParserFactory.java b/odata-core/src/main/java/org/odata4j/format/FormatParserFactory.java index 77a4c1a..8d0e05b 100644 --- a/odata-core/src/main/java/org/odata4j/format/FormatParserFactory.java +++ b/odata-core/src/main/java/org/odata4j/format/FormatParserFactory.java @@ -1,6 +1,6 @@ package org.odata4j.format; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.odata4j.core.OCollection; import org.odata4j.core.OComplexObject; @@ -25,7 +25,8 @@ public class FormatParserFactory { - private FormatParserFactory() {} + private FormatParserFactory() { + } private static interface FormatParsers { FormatParser getFeedFormatParser(Settings settings); @@ -69,7 +70,8 @@ public static FormatParser getParser(Class targetType, } else if (OEntity.class.isAssignableFrom(targetType)) { return (FormatParser) formatParsers.getEntityFormatParser(settings); } - throw new IllegalArgumentException("Unable to locate format parser for " + targetType.getName() + " and format " + type); + throw new IllegalArgumentException( + "Unable to locate format parser for " + targetType.getName() + " and format " + type); } public static FormatParser getParser(Class targetType, MediaType contentType, Settings settings) { @@ -77,7 +79,8 @@ public static FormatParser getParser(Class targetType, MediaType conte FormatType type; if (contentType.isCompatible(MediaType.APPLICATION_JSON_TYPE)) type = FormatType.JSON; - else if (contentType.isCompatible(MediaType.APPLICATION_ATOM_XML_TYPE) && (Feed.class.isAssignableFrom(targetType) || Entry.class.isAssignableFrom(targetType)) + else if (contentType.isCompatible(MediaType.APPLICATION_ATOM_XML_TYPE) + && (Feed.class.isAssignableFrom(targetType) || Entry.class.isAssignableFrom(targetType)) || contentType.isCompatible(MediaType.APPLICATION_XML_TYPE)) type = FormatType.ATOM; else diff --git a/odata-core/src/main/java/org/odata4j/format/FormatType.java b/odata-core/src/main/java/org/odata4j/format/FormatType.java index f3d883e..dc63498 100644 --- a/odata-core/src/main/java/org/odata4j/format/FormatType.java +++ b/odata-core/src/main/java/org/odata4j/format/FormatType.java @@ -1,6 +1,6 @@ package org.odata4j.format; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; public enum FormatType { diff --git a/odata-core/src/main/java/org/odata4j/format/FormatWriter.java b/odata-core/src/main/java/org/odata4j/format/FormatWriter.java index dc3122c..f60c175 100644 --- a/odata-core/src/main/java/org/odata4j/format/FormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/FormatWriter.java @@ -2,9 +2,10 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; -/** Write entities to an output stream in a particular format +/** + * Write entities to an output stream in a particular format * * @param the type of the entities to be written */ @@ -14,8 +15,8 @@ public interface FormatWriter { * Write an object to the formatted version of the stream * * @param uriInfo the base uri of the entity documents - * @param w the underlying "stream" to write to - * @param target the object to be written + * @param w the underlying "stream" to write to + * @param target the object to be written */ void write(UriInfo uriInfo, Writer w, T target); diff --git a/odata-core/src/main/java/org/odata4j/format/FormatWriterFactory.java b/odata-core/src/main/java/org/odata4j/format/FormatWriterFactory.java index 7501753..bc9a752 100644 --- a/odata-core/src/main/java/org/odata4j/format/FormatWriterFactory.java +++ b/odata-core/src/main/java/org/odata4j/format/FormatWriterFactory.java @@ -2,7 +2,7 @@ import java.util.List; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.odata4j.edm.EdmDataServices; import org.odata4j.format.json.JsonCollectionFormatWriter; @@ -51,7 +51,7 @@ private static interface FormatWriters { FormatWriter getPropertyFormatWriter(); FormatWriter getSimpleFormatWriter(); - + FormatWriter getRawFormatWriter(); FormatWriter getRequestEntryFormatWriter(); @@ -68,7 +68,8 @@ private static interface FormatWriters { } @SuppressWarnings("unchecked") - public static FormatWriter getFormatWriter(Class targetType, List acceptTypes, String format, String callback) { + public static FormatWriter getFormatWriter(Class targetType, List acceptTypes, String format, + String callback) { FormatType type = null; @@ -108,8 +109,8 @@ public static FormatWriter getFormatWriter(Class targetType, List) formatWriters.getSimpleFormatWriter(); if (targetType.equals(RawResponse.class)) - return (FormatWriter) formatWriters.getRawFormatWriter(); - + return (FormatWriter) formatWriters.getRawFormatWriter(); + if (Entry.class.isAssignableFrom(targetType)) return (FormatWriter) formatWriters.getRequestEntryFormatWriter(); @@ -128,7 +129,8 @@ public static FormatWriter getFormatWriter(Class targetType, List) formatWriters.getErrorFormatWriter(); - throw new IllegalArgumentException("Unable to locate format writer for " + targetType.getName() + " and format " + type); + throw new IllegalArgumentException( + "Unable to locate format writer for " + targetType.getName() + " and format " + type); } @@ -169,7 +171,7 @@ public FormatWriter getPropertyFormatWriter() { public FormatWriter getSimpleFormatWriter() { return new JsonSimpleFormatWriter(callback); } - + @Override public FormatWriter getRawFormatWriter() { return new JsonRawFormatWriter(); @@ -257,11 +259,11 @@ public FormatWriter> getCollectionFormatWriter() { public FormatWriter getSimpleFormatWriter() { return new AtomSimpleFormatWriter(); } - + @Override public FormatWriter getRawFormatWriter() { return new AtomRawFormatWriter(); - } + } @Override public FormatWriter getErrorFormatWriter() { diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonCollectionFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonCollectionFormatWriter.java index 5d65f25..9a0d6c3 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonCollectionFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonCollectionFormatWriter.java @@ -1,6 +1,6 @@ package org.odata4j.format.json; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.OCollection; import org.odata4j.core.OEntity; @@ -27,8 +27,7 @@ protected void writeContent(UriInfo uriInfo, JsonWriter jw, CollectionResponse { @@ -77,36 +77,49 @@ public void writeContent(UriInfo uriInfo, JsonWriter jw, EntitiesResponse target } /* - -// entities v2 -{ -"d" : { -"results": [ -{ -"__metadata": { -"uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(1)", "type": "ODataServices.ODataConsumer" -}, "Id": 1, "Name": "Browsers", "Description": "Most modern browsers allow you to browse Atom based feeds. Simply point your browser at one of the OData Producers.", "ApplicationUrl": "" -}, { -"__metadata": { -"uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(6)", "type": "ODataServices.ODataConsumer" -}, "Id": 6, "Name": "Sesame - OData Browser", "Description": "A preview version of Fabrice Marguerie\'s OData Browser.", "ApplicationUrl": "http://metasapiens.com/sesame/data-browser" -} -], "__count": "3", "__next": "http://odata.netflix.com/Catalog/Titles/?$filter=substringof('matrix',Name)&$skiptoken='IHKWS'" -} -} - -// entities v1 -{ -"d" : [ -{ -"__metadata": { -"uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(1)", "type": "ODataServices.ODataConsumer" -}, "Id": 1, "Name": "Browsers", "Description": "Most modern browsers allow you to browse Atom based feeds. Simply point your browser at one of the OData Producers.", "ApplicationUrl": "" -}, { -"__metadata": { -"uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(6)", "type": "ODataServices.ODataConsumer" -}, "Id": 6, "Name": "Sesame - OData Browser", "Description": "A preview version of Fabrice Marguerie\'s OData Browser.", "ApplicationUrl": "http://metasapiens.com/sesame/data-browser" -} -] -} + * + * // entities v2 + * { + * "d" : { + * "results": [ + * { + * "__metadata": { + * "uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(1)", + * "type": "ODataServices.ODataConsumer" + * }, "Id": 1, "Name": "Browsers", "Description": + * "Most modern browsers allow you to browse Atom based feeds. Simply point your browser at one of the OData Producers." + * , "ApplicationUrl": "" + * }, { + * "__metadata": { + * "uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(6)", + * "type": "ODataServices.ODataConsumer" + * }, "Id": 6, "Name": "Sesame - OData Browser", "Description": + * "A preview version of Fabrice Marguerie\'s OData Browser.", "ApplicationUrl": + * "http://metasapiens.com/sesame/data-browser" + * } + * ], "__count": "3", "__next": + * "http://odata.netflix.com/Catalog/Titles/?$filter=substringof('matrix',Name)&$skiptoken='IHKWS'" + * } + * } + * + * // entities v1 + * { + * "d" : [ + * { + * "__metadata": { + * "uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(1)", + * "type": "ODataServices.ODataConsumer" + * }, "Id": 1, "Name": "Browsers", "Description": + * "Most modern browsers allow you to browse Atom based feeds. Simply point your browser at one of the OData Producers." + * , "ApplicationUrl": "" + * }, { + * "__metadata": { + * "uri": "http://services.odata.org/Website/odata.svc/ODataConsumers(6)", + * "type": "ODataServices.ODataConsumer" + * }, "Id": 6, "Name": "Sesame - OData Browser", "Description": + * "A preview version of Fabrice Marguerie\'s OData Browser.", "ApplicationUrl": + * "http://metasapiens.com/sesame/data-browser" + * } + * ] + * } */ diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonFormatWriter.java index de3208b..1934a9a 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonFormatWriter.java @@ -5,7 +5,7 @@ import java.util.Iterator; import java.util.List; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; @@ -34,10 +34,12 @@ /** * Write content to an output stream in JSON format. * - *

This class is abstract because it delegates the strategy pattern of writing + *

+ * This class is abstract because it delegates the strategy pattern of writing * actual content elements to its (various) subclasses. * - *

Each element in the array to be written can be wrapped in a function call + *

+ * Each element in the array to be written can be wrapped in a function call * on the JavaScript side by specifying the name of a function to call to the * constructor. * @@ -51,7 +53,7 @@ public abstract class JsonFormatWriter implements FormatWriter { * Creates a new JSON writer. * * @param jsonpCallback a function to call on the javascript side to act - * on the data provided in the content. + * on the data provided in the content. */ public JsonFormatWriter(String jsonpCallback) { this.jsonpCallback = jsonpCallback; @@ -61,8 +63,8 @@ public JsonFormatWriter(String jsonpCallback) { * A strategy method to actually write content objects * * @param uriInfo the base URI that indicates where in the schema we are - * @param jw the JSON writer object - * @param target the content value to be written + * @param jw the JSON writer object + * @param target the content value to be written */ abstract protected void writeContent(UriInfo uriInfo, JsonWriter jw, T target); @@ -135,7 +137,8 @@ protected void writeValue(JsonWriter jw, EdmType type, Object pvalue) { jw.writeRaw(InternalUtil.formatTimeForJson((LocalTime) pvalue)); } else if (type.equals(EdmSimpleType.DATETIMEOFFSET)) { jw.writeRaw(InternalUtil.formatDateTimeOffsetForJson((DateTime) pvalue)); - } else if (type instanceof EdmComplexType || (type instanceof EdmSimpleType && (!((EdmSimpleType) type).isSimple()))) { + } else if (type instanceof EdmComplexType + || (type instanceof EdmSimpleType && (!((EdmSimpleType) type).isSimple()))) { // the OComplexObject value type is not in use everywhere yet, fix TODO if (pvalue instanceof OComplexObject) { pvalue = ((OComplexObject) pvalue).getProperties(); @@ -167,19 +170,23 @@ protected void writeCollection(JsonWriter jw, EdmCollectionType type, OCollectio jw.writeSeparator(); } if (obj instanceof OComplexObject) { - writeComplexObject(jw, null, obj.getType().getFullyQualifiedTypeName(), ((OComplexObject) obj).getProperties()); + writeComplexObject(jw, null, obj.getType().getFullyQualifiedTypeName(), + ((OComplexObject) obj).getProperties()); } else if (obj instanceof OSimpleObject) { writeValue(jw, obj.getType(), ((OSimpleObject) obj).getValue()); } else if (obj instanceof OCollection) { - writeCollection(jw, type, (OCollection)obj); + writeCollection(jw, type, (OCollection) obj); } - //else if (obj instanceof OEntity) { - // I think the FormatWriter sig is going to have to change: - // 2. why does JSON write absolute uris (http://blah/blah) for every entity? The Atom - // equivalent parts have the relative uri in many places. Hmmh, a JSON feed representation - // doesn't carry the xml:base uri like in Atom...weird...protocol seems inconsistent. - // this.writeOEntity(null, jw, null, null, isFirst); - //} + // else if (obj instanceof OEntity) { + // I think the FormatWriter sig is going to have to change: + // 2. why does JSON write absolute uris (http://blah/blah) for every entity? The + // Atom + // equivalent parts have the relative uri in many places. Hmmh, a JSON feed + // representation + // doesn't carry the xml:base uri like in Atom...weird...protocol seems + // inconsistent. + // this.writeOEntity(null, jw, null, null, isFirst); + // } // others for later: ORowType } @@ -189,20 +196,22 @@ protected void writeCollection(JsonWriter jw, EdmCollectionType type, OCollectio jw.endObject(); } - protected void writeComplexObject(JsonWriter jw, String complexObjectName, String fullyQualifiedTypeName, List> props) { + protected void writeComplexObject(JsonWriter jw, String complexObjectName, String fullyQualifiedTypeName, + List> props) { jw.startObject(); { - /* Confused: The live OData producers that have complex types (ebay, netflix) - * both write this __metadata object for each complex object. I can't find + /* + * Confused: The live OData producers that have complex types (ebay, netflix) + * both write this __metadata object for each complex object. I can't find * this in the OData spec though... - jw.writeName("__metadata"); - jw.startObject(); - { - jw.writeName("type"); - jw.writeString(fullyQualifiedTypeName); - } - jw.endObject(); - jw.writeSeparator(); + * jw.writeName("__metadata"); + * jw.startObject(); + * { + * jw.writeName("type"); + * jw.writeString(fullyQualifiedTypeName); + * } + * jw.endObject(); + * jw.writeSeparator(); */ if (complexObjectName != null) { jw.writeName(complexObjectName); @@ -222,8 +231,10 @@ protected void writeOEntity(UriInfo uriInfo, JsonWriter jw, OEntity oe, EdmEntit { String baseUri = null; - // TODO: I'm keeping this pattern of writing the __metadata if we have a non-null type..it seems like we could still - // write the uri even if we don't have a type. Also, are there any scenarios where the entity type would be null? Not sure. + // TODO: I'm keeping this pattern of writing the __metadata if we have a + // non-null type..it seems like we could still + // write the uri even if we don't have a type. Also, are there any scenarios + // where the entity type would be null? Not sure. if (isResponse && oe.getEntityType() != null) { baseUri = uriInfo.getBaseUri().toString(); @@ -267,8 +278,8 @@ protected void writeResponseLink(JsonWriter jw, OLink link, OEntity oe, UriInfo if (link.isCollection()) { // the version check will only make sense when this library properly - // supports version negotiation. For now we write v2 only - if (true) { // || ODataVersion.isVersionGreaterThan(settings.version, ODataVersion.V1)) { + // supports version negotiation. For now we write v2 only + if (true) { // || ODataVersion.isVersionGreaterThan(settings.version, ODataVersion.V1)) { jw.startObject(); jw.writeName(JsonFormatParser.RESULTS_PROPERTY); } diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonPropertyFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonPropertyFormatWriter.java index 0108773..fb3c55d 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonPropertyFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonPropertyFormatWriter.java @@ -1,6 +1,6 @@ package org.odata4j.format.json; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.producer.PropertyResponse; @@ -22,10 +22,10 @@ protected void writeContent(UriInfo uriInfo, JsonWriter jw, PropertyResponse tar } /* -// property -{ -"d" : { -"CategoryName": "Beverages" -} -} -*/ + * // property + * { + * "d" : { + * "CategoryName": "Beverages" + * } + * } + */ diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonRawFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonRawFormatWriter.java index f0f229e..3de54a3 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonRawFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonRawFormatWriter.java @@ -4,7 +4,7 @@ import java.io.Writer; import java.math.BigDecimal; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; @@ -25,89 +25,89 @@ public class JsonRawFormatWriter implements FormatWriter { @Override public void write(UriInfo uriInfo, Writer w, RawResponse target) { - EdmType type = target.getType(); - Object value = target.getValue(); - String sValue = null; + EdmType type = target.getType(); + Object value = target.getValue(); + String sValue = null; if (type.isSimple()) { - // simple - // now write the value - if (type == EdmSimpleType.INT32) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.INT16) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.INT64) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.BOOLEAN) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.BYTE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.SBYTE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.DECIMAL) { - if (value != null) { - sValue = ((BigDecimal) value).toPlainString(); - } - } else if (type == EdmSimpleType.SINGLE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.DOUBLE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.STRING) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.DATETIME) { - if (value != null) - sValue = InternalUtil.formatDateTimeForXml( - (LocalDateTime) value); - } else if (type == EdmSimpleType.BINARY) { - byte[] bValue = (byte[]) value; - if (value != null) { - sValue = Base64.encodeBase64String(bValue); - } - } else if (type == EdmSimpleType.GUID) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.TIME) { - if (value != null) { - sValue = InternalUtil.formatTimeForXml((LocalTime) value); - } - } else if (type == EdmSimpleType.DATETIMEOFFSET) { - // Edm.DateTimeOffset '-'? yyyy '-' mm '-' dd 'T' hh ':' mm - // ':' ss ('.' s+)? (zzzzzz)? - if (value != null) { - sValue = InternalUtil.formatDateTimeOffsetForXml((DateTime) value); - } + // simple + // now write the value + if (type == EdmSimpleType.INT32) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.INT16) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.INT64) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.BOOLEAN) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.BYTE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.SBYTE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.DECIMAL) { + if (value != null) { + sValue = ((BigDecimal) value).toPlainString(); + } + } else if (type == EdmSimpleType.SINGLE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.DOUBLE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.STRING) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.DATETIME) { + if (value != null) + sValue = InternalUtil.formatDateTimeForXml( + (LocalDateTime) value); + } else if (type == EdmSimpleType.BINARY) { + byte[] bValue = (byte[]) value; + if (value != null) { + sValue = Base64.encodeBase64String(bValue); + } + } else if (type == EdmSimpleType.GUID) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.TIME) { + if (value != null) { + sValue = InternalUtil.formatTimeForXml((LocalTime) value); + } + } else if (type == EdmSimpleType.DATETIMEOFFSET) { + // Edm.DateTimeOffset '-'? yyyy '-' mm '-' dd 'T' hh ':' mm + // ':' ss ('.' s+)? (zzzzzz)? + if (value != null) { + sValue = InternalUtil.formatDateTimeOffsetForXml((DateTime) value); + } + } else { + throw new UnsupportedOperationException("Implement " + target.getType()); + } + try { + if (sValue == null) { + w.write("null"); } else { - throw new UnsupportedOperationException("Implement " + target.getType()); + w.write(sValue); } - try { - if (sValue == null) { - w.write("null"); - } else { - w.write(sValue); - } - } catch (IOException e) { - throw Throwables.propagate(e); - } + } catch (IOException e) { + throw Throwables.propagate(e); + } } - } + } @Override public String getContentType() { diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonRequestEntryFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonRequestEntryFormatWriter.java index 2c1454d..0f36869 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonRequestEntryFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonRequestEntryFormatWriter.java @@ -2,8 +2,8 @@ import java.io.Writer; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.format.Entry; diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonServiceDocumentFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonServiceDocumentFormatWriter.java index 44dbb0a..e406f9b 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonServiceDocumentFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonServiceDocumentFormatWriter.java @@ -1,6 +1,6 @@ package org.odata4j.format.json; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.edm.EdmDataServices; import org.odata4j.edm.EdmEntitySet; @@ -40,21 +40,23 @@ public void writeContent(UriInfo uriInfo, JsonWriter jw, EdmDataServices target) } /* -// jsonp -callback({ -"d" : { -"EntitySets": [ -"TitleAudioFormats", "TitleAwards", "Titles", "TitleScreenFormats", "Genres", "Languages", "People" -] -} -}); - -// json -{ -"d" : { -"EntitySets": [ -"TitleAudioFormats", "TitleAwards", "Titles", "TitleScreenFormats", "Genres", "Languages", "People" -] -} -} -*/ \ No newline at end of file + * // jsonp + * callback({ + * "d" : { + * "EntitySets": [ + * "TitleAudioFormats", "TitleAwards", "Titles", "TitleScreenFormats", "Genres", + * "Languages", "People" + * ] + * } + * }); + * + * // json + * { + * "d" : { + * "EntitySets": [ + * "TitleAudioFormats", "TitleAwards", "Titles", "TitleScreenFormats", "Genres", + * "Languages", "People" + * ] + * } + * } + */ \ No newline at end of file diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonSimpleFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonSimpleFormatWriter.java index 69d811e..60b811a 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonSimpleFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonSimpleFormatWriter.java @@ -1,6 +1,6 @@ package org.odata4j.format.json; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.producer.SimpleResponse; diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinkFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinkFormatWriter.java index b48f24f..db7f075 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinkFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinkFormatWriter.java @@ -1,6 +1,6 @@ package org.odata4j.format.json; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.format.SingleLink; @@ -27,9 +27,9 @@ static void writeUri(JsonWriter jw, SingleLink link) { } /* -{ -"d" : { -"uri": "http://services.odata.org/northwind/Northwind.svc/Categories(1)" -} -} -*/ + * { + * "d" : { + * "uri": "http://services.odata.org/northwind/Northwind.svc/Categories(1)" + * } + * } + */ diff --git a/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinksFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinksFormatWriter.java index 59a63f0..770669f 100644 --- a/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinksFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/json/JsonSingleLinksFormatWriter.java @@ -1,6 +1,6 @@ package org.odata4j.format.json; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.format.SingleLink; import org.odata4j.format.SingleLinks; @@ -33,15 +33,17 @@ protected void writeContent(UriInfo uriInfo, JsonWriter jw, SingleLinks links) { } /* -{ -"d" : { -"results": [ -{ -"uri": "http://services.odata.org/northwind/Northwind.svc/Order_Details(OrderID=10285,ProductID=1)" -}, { -"uri": "http://services.odata.org/northwind/Northwind.svc/Order_Details(OrderID=10294,ProductID=1)" -} -] -} -} -*/ + * { + * "d" : { + * "results": [ + * { + * "uri": + * "http://services.odata.org/northwind/Northwind.svc/Order_Details(OrderID=10285,ProductID=1)" + * }, { + * "uri": + * "http://services.odata.org/northwind/Northwind.svc/Order_Details(OrderID=10294,ProductID=1)" + * } + * ] + * } + * } + */ diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomCollectionFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomCollectionFormatWriter.java index cf06693..06b4702 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomCollectionFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomCollectionFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.OCollection; import org.odata4j.core.ODataConstants; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomComplexFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomComplexFormatWriter.java index 14c0180..9167bfe 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomComplexFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomComplexFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.OComplexObject; import org.odata4j.core.ODataConstants; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomEntryFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomEntryFormatWriter.java index 3c1bf4e..d8ff461 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomEntryFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomEntryFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -61,7 +61,8 @@ public void write(UriInfo uriInfo, Writer w, EntityResponse target) { writer.writeNamespace("d", d); writer.writeAttribute("xml:base", baseUri); - writeEntry(writer, target.getEntity(), target.getEntity().getProperties(), target.getEntity().getLinks(), baseUri, updated, ees, true); + writeEntry(writer, target.getEntity(), target.getEntity().getProperties(), target.getEntity().getLinks(), baseUri, + updated, ees, true); writer.endDocument(); } diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomErrorFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomErrorFormatWriter.java index 375cd7f..ef2831a 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomErrorFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomErrorFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.core.OError; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatParser.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatParser.java index 41df5e2..de1d715 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatParser.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatParser.java @@ -7,7 +7,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.core4j.Enumerable; import org.core4j.Func1; @@ -187,9 +187,9 @@ AtomFeed parseFeed(XMLEventReader2 reader, EdmEntitySet entitySet) { } - public static Iterable> parseProperties( - XMLEventReader2 reader, StartElement2 propertiesElement, - EdmDataServices metadata, EdmStructuralType structuralType) { + public static Iterable> parseProperties( + XMLEventReader2 reader, StartElement2 propertiesElement, + EdmDataServices metadata, EdmStructuralType structuralType) { List> rt = new ArrayList>(); while (reader.hasNext()) { @@ -207,76 +207,78 @@ public static Iterable> parseProperties( throw new RuntimeException(); } -private static OProperty parseProperty(XMLEventReader2 reader, - EdmDataServices metadata, EdmStructuralType structuralType, - XMLEvent2 event) { - String name = event.asStartElement().getName().getLocalPart(); - Attribute2 typeAttribute = event.asStartElement().getAttributeByName(M_TYPE); - Attribute2 nullAttribute = event.asStartElement().getAttributeByName(M_NULL); - boolean isNull = nullAttribute != null && "true".equals(nullAttribute.getValue()); - - OProperty op = null; - - EdmType et = null; - if (typeAttribute != null) { - String type = typeAttribute.getValue(); - et = metadata.resolveType(type); - if (et == null) { - // property arrived with an unknown type - throw new RuntimeException("unknown property type: " + type); - } - } else { - EdmProperty property = (EdmProperty) structuralType.findProperty(name); - if (property != null) - et = property.getType(); - else - et = EdmSimpleType.STRING; // we must support open types - } - - if (et instanceof EdmCollectionType) { - op = readCollection(name, (EdmCollectionType)et, reader, event.asStartElement(), metadata, structuralType); - } else { - if (et != null && !et.isSimple()) { - EdmStructuralType est = (EdmStructuralType) et; - op = OProperties.complex(name, (EdmComplexType) et, isNull ? null : Enumerable.create(parseProperties(reader, event.asStartElement(), metadata, est)).toList()); - } else { - op = OProperties.parseSimple(name, (EdmSimpleType) et, isNull ? null : reader.getElementText()); - } - } - return op; -} + private static OProperty parseProperty(XMLEventReader2 reader, + EdmDataServices metadata, EdmStructuralType structuralType, + XMLEvent2 event) { + String name = event.asStartElement().getName().getLocalPart(); + Attribute2 typeAttribute = event.asStartElement().getAttributeByName(M_TYPE); + Attribute2 nullAttribute = event.asStartElement().getAttributeByName(M_NULL); + boolean isNull = nullAttribute != null && "true".equals(nullAttribute.getValue()); + + OProperty op = null; + + EdmType et = null; + if (typeAttribute != null) { + String type = typeAttribute.getValue(); + et = metadata.resolveType(type); + if (et == null) { + // property arrived with an unknown type + throw new RuntimeException("unknown property type: " + type); + } + } else { + EdmProperty property = (EdmProperty) structuralType.findProperty(name); + if (property != null) + et = property.getType(); + else + et = EdmSimpleType.STRING; // we must support open types + } - private static OProperty readCollection(String name, - EdmCollectionType collectionType, XMLEventReader2 reader, - StartElement2 collectionElement, EdmDataServices metadata, EdmStructuralType structuralType) { - EdmType componentType = collectionType.getItemType(); - - OCollection.Builder b = OCollections.newBuilder(componentType); + if (et instanceof EdmCollectionType) { + op = readCollection(name, (EdmCollectionType) et, reader, event.asStartElement(), metadata, structuralType); + } else { + if (et != null && !et.isSimple()) { + EdmStructuralType est = (EdmStructuralType) et; + op = OProperties.complex(name, (EdmComplexType) et, + isNull ? null : Enumerable.create(parseProperties(reader, event.asStartElement(), metadata, est)).toList()); + } else { + op = OProperties.parseSimple(name, (EdmSimpleType) et, isNull ? null : reader.getElementText()); + } + } + return op; + } + + private static OProperty readCollection(String name, + EdmCollectionType collectionType, XMLEventReader2 reader, + StartElement2 collectionElement, EdmDataServices metadata, EdmStructuralType structuralType) { + EdmType componentType = collectionType.getItemType(); + + OCollection.Builder b = OCollections.newBuilder(componentType); while (reader.hasNext()) { - XMLEvent2 event = reader.nextEvent(); + XMLEvent2 event = reader.nextEvent(); - if (event.isEndElement() && event.asEndElement().getName().equals(collectionElement.getName())) { - break; - } + if (event.isEndElement() && event.asEndElement().getName().equals(collectionElement.getName())) { + break; + } - if (event.isStartElement() && event.asStartElement().getName().getNamespaceUri().equals(NS_DATASERVICES)) { - OProperty op = null; - Attribute2 nullAttribute = event.asStartElement().getAttributeByName(M_NULL); - boolean isNull = nullAttribute != null && "true".equals(nullAttribute.getValue()); - if (!componentType.isSimple()) { - EdmStructuralType est = (EdmStructuralType) componentType; - op = OProperties.complex(name, (EdmComplexType) componentType, isNull ? null : Enumerable.create(parseProperties(reader, event.asStartElement(), metadata, est)).toList()); - } else { - op = OProperties.parseSimple(name, (EdmSimpleType) componentType, isNull ? null : reader.getElementText()); - } - b.add(OSimpleObjects.create((EdmSimpleType)componentType, op.getValue())); + if (event.isStartElement() && event.asStartElement().getName().getNamespaceUri().equals(NS_DATASERVICES)) { + OProperty op = null; + Attribute2 nullAttribute = event.asStartElement().getAttributeByName(M_NULL); + boolean isNull = nullAttribute != null && "true".equals(nullAttribute.getValue()); + if (!componentType.isSimple()) { + EdmStructuralType est = (EdmStructuralType) componentType; + op = OProperties.complex(name, (EdmComplexType) componentType, isNull ? null + : Enumerable.create(parseProperties(reader, event.asStartElement(), metadata, est)).toList()); + } else { + op = OProperties.parseSimple(name, (EdmSimpleType) componentType, isNull ? null : reader.getElementText()); } + b.add(OSimpleObjects.create((EdmSimpleType) componentType, op.getValue())); + } } - return OProperties.collection(name, collectionType, b.build()); -} + return OProperties.collection(name, collectionType, b.build()); + } -private AtomLink parseAtomLink(XMLEventReader2 reader, StartElement2 linkElement, EdmEntitySet entitySet) { + private AtomLink parseAtomLink(XMLEventReader2 reader, StartElement2 linkElement, EdmEntitySet entitySet) { AtomLink rt = new AtomLink(); rt.relation = getAttributeValueIfExists(linkElement, "rel"); rt.type = getAttributeValueIfExists(linkElement, "type"); @@ -293,10 +295,11 @@ private AtomLink parseAtomLink(XMLEventReader2 reader, StartElement2 linkElement targetEntitySet = metadata.getEdmEntitySet(navProperty.getToRole().getType()); // expected cases: - // 1. - no inlined content, i.e. deferred - // 2. - inlined content but null entity or empty feed - // 3. ... - inlined content with 1 or more items - // 4. .. - inlined content 1 an item + // 1. - no inlined content, i.e. deferred + // 2. - inlined content but null entity or empty feed + // 3. ... - inlined content with 1 or more + // items + // 4. .. - inlined content 1 an item while (reader.hasNext()) { XMLEvent2 event = reader.nextEvent(); @@ -314,8 +317,10 @@ private AtomLink parseAtomLink(XMLEventReader2 reader, StartElement2 linkElement return rt; } - private DataServicesAtomEntry parseDSAtomEntry(String etag, EdmEntityType entityType, XMLEventReader2 reader, XMLEvent2 event) { - List> properties = Enumerable.create(parseProperties(reader, event.asStartElement(), metadata, entityType)).toList(); + private DataServicesAtomEntry parseDSAtomEntry(String etag, EdmEntityType entityType, XMLEventReader2 reader, + XMLEvent2 event) { + List> properties = Enumerable + .create(parseProperties(reader, event.asStartElement(), metadata, entityType)).toList(); return new DataServicesAtomEntry(etag, properties); } @@ -380,12 +385,12 @@ private AtomEntry parseEntry(XMLEventReader2 reader, StartElement2 entryElement, XMLEvent2 event = reader.nextEvent(); if (event.isEndElement() && event.asEndElement().getName().equals(entryElement.getName())) { - rt.id = id; //http://localhost:8810/Oneoff01.svc/Comment(1) + rt.id = id; // http://localhost:8810/Oneoff01.svc/Comment(1) rt.title = title; rt.summary = summary; rt.updated = updated; - rt.categoryScheme = categoryScheme; //http://schemas.microsoft.com/ado/2007/08/dataservices/scheme - rt.categoryTerm = categoryTerm; //NorthwindModel.Customer + rt.categoryScheme = categoryScheme; // http://schemas.microsoft.com/ado/2007/08/dataservices/scheme + rt.categoryTerm = categoryTerm; // NorthwindModel.Customer rt.contentType = contentType; rt.atomLinks = atomLinks; @@ -564,8 +569,8 @@ public OEntity apply( link.title, link.href, relatedEntity)); } else { // no inlined entity - rt.add(OLinks.relatedEntity(link.relation, link.title, link.href)); - } + rt.add(OLinks.relatedEntity(link.relation, link.title, link.href)); + } } } return rt; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatWriter.java index 4dcc63d..7a1fd89 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomFeedFormatWriter.java @@ -3,8 +3,8 @@ import java.io.Writer; import java.util.List; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriBuilder; +import jakarta.ws.rs.core.UriInfo; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -44,7 +44,7 @@ public void write(UriInfo uriInfo, Writer w, EntitiesResponse response) { writer.writeAttribute("xml:base", baseUri); writeElement(writer, "title", entitySetName, "type", "text"); - String path = uriInfo.getPath(); + String path = uriInfo.getPath(); if (baseUri.endsWith("/") && path.startsWith("/")) { path = path.substring(1); } @@ -66,7 +66,9 @@ public void write(UriInfo uriInfo, Writer w, EntitiesResponse response) { } if (response.getSkipToken() != null) { - // + // UriBuilder builder = uriInfo.getRequestUriBuilder().replaceQueryParam("$skiptoken", response.getSkipToken()); List topParam = uriInfo.getQueryParameters().get("$top"); if (topParam != null) { diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomRawFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomRawFormatWriter.java index e25dcbd..553d649 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomRawFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomRawFormatWriter.java @@ -4,7 +4,7 @@ import java.io.Writer; import java.math.BigDecimal; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; @@ -22,87 +22,87 @@ public class AtomRawFormatWriter extends XmlFormatWriter implements FormatWriter @Override public void write(UriInfo uriInfo, Writer w, RawResponse target) { - EdmType type = target.getType(); - Object value = target.getValue(); - String sValue = null; + EdmType type = target.getType(); + Object value = target.getValue(); + String sValue = null; if (type.isSimple()) { - // simple - // now write the value - if (type == EdmSimpleType.INT32) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.INT16) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.INT64) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.BOOLEAN) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.BYTE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.SBYTE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.DECIMAL) { - if (value != null) { - sValue = ((BigDecimal) value).toPlainString(); - } - } else if (type == EdmSimpleType.SINGLE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.DOUBLE) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.STRING) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.DATETIME) { - if (value != null) - sValue = InternalUtil.formatDateTimeForXml( - (LocalDateTime) value); - } else if (type == EdmSimpleType.BINARY) { - byte[] bValue = (byte[]) value; - if (value != null) { - sValue = Base64.encodeBase64String(bValue); - } - } else if (type == EdmSimpleType.GUID) { - if (value != null) { - sValue = value.toString(); - } - } else if (type == EdmSimpleType.TIME) { - if (value != null) { - sValue = InternalUtil.formatTimeForXml((LocalTime) value); - } - } else if (type == EdmSimpleType.DATETIMEOFFSET) { - // Edm.DateTimeOffset '-'? yyyy '-' mm '-' dd 'T' hh ':' mm - // ':' ss ('.' s+)? (zzzzzz)? - if (value != null) { - sValue = InternalUtil.formatDateTimeOffsetForXml((DateTime) value); - } + // simple + // now write the value + if (type == EdmSimpleType.INT32) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.INT16) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.INT64) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.BOOLEAN) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.BYTE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.SBYTE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.DECIMAL) { + if (value != null) { + sValue = ((BigDecimal) value).toPlainString(); + } + } else if (type == EdmSimpleType.SINGLE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.DOUBLE) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.STRING) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.DATETIME) { + if (value != null) + sValue = InternalUtil.formatDateTimeForXml( + (LocalDateTime) value); + } else if (type == EdmSimpleType.BINARY) { + byte[] bValue = (byte[]) value; + if (value != null) { + sValue = Base64.encodeBase64String(bValue); + } + } else if (type == EdmSimpleType.GUID) { + if (value != null) { + sValue = value.toString(); + } + } else if (type == EdmSimpleType.TIME) { + if (value != null) { + sValue = InternalUtil.formatTimeForXml((LocalTime) value); + } + } else if (type == EdmSimpleType.DATETIMEOFFSET) { + // Edm.DateTimeOffset '-'? yyyy '-' mm '-' dd 'T' hh ':' mm + // ':' ss ('.' s+)? (zzzzzz)? + if (value != null) { + sValue = InternalUtil.formatDateTimeOffsetForXml((DateTime) value); + } + } else { + throw new UnsupportedOperationException("Implement " + target.getType()); + } + try { + if (sValue == null) { + w.write("null"); } else { - throw new UnsupportedOperationException("Implement " + target.getType()); + w.write(sValue); } - try { - if (sValue == null) { - w.write("null"); - } else { - w.write(sValue); - } - } catch (IOException e) { - throw Throwables.propagate(e); - } + } catch (IOException e) { + throw Throwables.propagate(e); + } } } diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomRequestEntryFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomRequestEntryFormatWriter.java index 455d7a3..6ce3260 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomRequestEntryFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomRequestEntryFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.format.Entry; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomServiceDocumentFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomServiceDocumentFormatWriter.java index 2ee2a85..b5942a7 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomServiceDocumentFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomServiceDocumentFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.edm.EdmDataServices; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomSimpleFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomSimpleFormatWriter.java index e1db421..9ee5506 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomSimpleFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomSimpleFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.format.FormatWriter; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinkFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinkFormatWriter.java index ca67496..222532a 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinkFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinkFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.format.FormatWriter; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinksFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinksFormatWriter.java index 8f4da45..cea371a 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinksFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/AtomSingleLinksFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.format.FormatWriter; diff --git a/odata-core/src/main/java/org/odata4j/format/xml/XmlFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/XmlFormatWriter.java index 12d6d82..0eff8a7 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/XmlFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/XmlFormatWriter.java @@ -4,7 +4,7 @@ import java.util.Iterator; import java.util.List; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -54,7 +54,8 @@ protected void writeProperty(XMLWriter2 writer, OProperty prop, boolean isDoc } @SuppressWarnings("unchecked") - protected void writeProperty(XMLWriter2 writer, String name, EdmType type, Object value, boolean isDocumentElement, boolean writeType) { + protected void writeProperty(XMLWriter2 writer, String name, EdmType type, Object value, boolean isDocumentElement, + boolean writeType) { writer.startElement(new QName2(d, name, "d")); @@ -268,7 +269,7 @@ protected String writeEntry(XMLWriter2 writer, OEntity oe, // for requests we include only the provided links // Note: It seems that OLinks for responses are only built using the // title and OLinks for requests have the additional info in them - // alread. I'm leaving that inconsistency in place for now but this + // alread. I'm leaving that inconsistency in place for now but this // else and its preceding if could probably be unified. for (OLink olink : entityLinks) { String type = olink.isCollection() @@ -404,12 +405,16 @@ private void writeCollection(XMLWriter2 writer, String name, OCollection)o).getType().getFullyQualifiedTypeName()+")"); - writeCollection(writer, "element", (OCollection)o); - writer.endElement("d:element"); + writer.startElement("d:element"); + writer.writeAttribute("m:type", + "Collection(" + ((OCollection) o).getType().getFullyQualifiedTypeName() + ")"); + writeCollection(writer, "element", (OCollection) o); + writer.endElement("d:element"); } else { // TODO... } diff --git a/odata-core/src/main/java/org/odata4j/format/xml/XmlPropertyFormatWriter.java b/odata-core/src/main/java/org/odata4j/format/xml/XmlPropertyFormatWriter.java index faf07ad..c84aa9d 100644 --- a/odata-core/src/main/java/org/odata4j/format/xml/XmlPropertyFormatWriter.java +++ b/odata-core/src/main/java/org/odata4j/format/xml/XmlPropertyFormatWriter.java @@ -2,7 +2,7 @@ import java.io.Writer; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.format.FormatWriter; diff --git a/odata-core/src/main/java/org/odata4j/internal/InternalUtil.java b/odata-core/src/main/java/org/odata4j/internal/InternalUtil.java index 866601b..95b3940 100644 --- a/odata-core/src/main/java/org/odata4j/internal/InternalUtil.java +++ b/odata-core/src/main/java/org/odata4j/internal/InternalUtil.java @@ -59,10 +59,12 @@ public class InternalUtil { private static final DateTimeFormatter DATETIME_XML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm"); private static final DateTimeFormatter DATETIME_WITH_SECONDS_XML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"); - private static final DateTimeFormatter DATETIME_WITH_MILLIS_XML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); + private static final DateTimeFormatter DATETIME_WITH_MILLIS_XML = DateTimeFormat + .forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); private static final DateTimeFormatter DATETIMEOFFSET_XML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ"); - private static final DateTimeFormatter DATETIMEOFFSET_WITH_MILLIS_XML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ"); + private static final DateTimeFormatter DATETIMEOFFSET_WITH_MILLIS_XML = DateTimeFormat + .forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ"); private static final String DATETIME_JSON_SUFFIX = ")\\/\""; private static final String DATETIME_JSON_PREFIX = "\"\\/Date("; @@ -88,7 +90,8 @@ public static LocalDateTime parseDateTimeFromXml(String value) { if (nanoSeconds.length() <= 4) return DATETIME_WITH_MILLIS_XML.parseDateTime(dateTime + seconds + nanoSeconds).toLocalDateTime(); - return adjustMillis(DATETIME_WITH_MILLIS_XML.parseDateTime(dateTime + seconds + nanoSeconds.substring(0, 4)), nanoSeconds).toLocalDateTime(); + return adjustMillis(DATETIME_WITH_MILLIS_XML.parseDateTime(dateTime + seconds + nanoSeconds.substring(0, 4)), + nanoSeconds).toLocalDateTime(); } throw new IllegalArgumentException("Illegal datetime format " + value); } @@ -115,7 +118,8 @@ public static DateTime parseDateTimeOffsetFromXml(String value) { if (nanoSeconds.length() <= 4) return DATETIMEOFFSET_WITH_MILLIS_XML.withOffsetParsed().parseDateTime(dateTime + nanoSeconds + offset); - return adjustMillis(DATETIMEOFFSET_WITH_MILLIS_XML.withOffsetParsed().parseDateTime(dateTime + nanoSeconds.substring(0, 4) + offset), nanoSeconds); + return adjustMillis(DATETIMEOFFSET_WITH_MILLIS_XML.withOffsetParsed() + .parseDateTime(dateTime + nanoSeconds.substring(0, 4) + offset), nanoSeconds); } throw new IllegalArgumentException("Illegal datetimeoffset format " + value); } @@ -199,7 +203,8 @@ public static String formatDateTimeForJson(LocalDateTime localDateTime) { public static String formatDateTimeOffsetForJson(DateTime dateTime) { long millis = dateTime.getMillis(); int offsetInMillis = dateTime.getZone().getOffset(millis); - return DATETIME_JSON_PREFIX + (millis - offsetInMillis) + String.format(Locale.US, "%+05d", offsetInMillis / 1000 / 60) + DATETIME_JSON_SUFFIX; + return DATETIME_JSON_PREFIX + (millis - offsetInMillis) + + String.format(Locale.US, "%+05d", offsetInMillis / 1000 / 60) + DATETIME_JSON_SUFFIX; } public static String formatTimeForXml(LocalTime localTime) { @@ -269,16 +274,16 @@ public static T toPojo(Class pojoClass, OEntity oe) { if (beanModel.canWrite(ol.getTitle())) { Collection relatedEntities = ol .getRelatedEntities() == null - ? null - : Enumerable.create(ol.getRelatedEntities()) - .select(new Func1() { - @Override - public Object apply(OEntity input) { - return toPojo( - beanModel.getCollectionElementType(collectionName), - input); - } - }).toList(); + ? null + : Enumerable.create(ol.getRelatedEntities()) + .select(new Func1() { + @Override + public Object apply(OEntity input) { + return toPojo( + beanModel.getCollectionElementType(collectionName), + input); + } + }).toList(); beanModel.setCollectionValue(rt, collectionName, relatedEntities); } @@ -361,4 +366,22 @@ public static void copyInputToOutput(InputStream inStream, OutputStream outStrea } outStream.flush(); } + + /** + * Returns the system property value for the passed key. + * + * @param key + * the key + * @return the system property value + */ + public static String getSystemPropertyValue(String key) { + String value = null; + + value = System.getProperty(key); + if (value == null) { + value = System.getenv(key); + } + + return value; + } } diff --git a/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtension.java b/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtension.java index d5e5431..93258f3 100644 --- a/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtension.java +++ b/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtension.java @@ -1,7 +1,7 @@ package org.odata4j.producer; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.OExtension; import org.odata4j.exceptions.ODataProducerException; @@ -9,23 +9,30 @@ /** * An optional extension that a producer can expose to control error responses. * - *

To expose this extension, the producer implementation has to return an instance of this - * interface when method {@code findExtension} is called and the first parameter is equal to - * {@code ErrorResponseExtension.class}.

+ *

+ * To expose this extension, the producer implementation has to return an + * instance of this + * interface when method {@code findExtension} is called and the first parameter + * is equal to + * {@code ErrorResponseExtension.class}. + *

* * @see ErrorResponseExtensions */ public interface ErrorResponseExtension extends OExtension { /** - * This method is called before an error response is created and sent to the client. Thus - * producers can decide if an inner error should be returned or not. This decision can be based + * This method is called before an error response is created and sent to the + * client. Thus + * producers can decide if an inner error should be returned or not. This + * decision can be based * on a system property, a query parameter, or any other data source. * - * @param httpHeaders the HTTP headers of the request that led to an error - * @param uriInfo the URI info of the request that led to an error - * @param exception the exception about to be sent to the client - * @return flag indicating whether to return an inner error as part of the error response to the + * @param httpHeaders the HTTP headers of the request that led to an error + * @param uriInfo the URI info of the request that led to an error + * @param exception the exception about to be sent to the client + * @return flag indicating whether to return an inner error as part of the error + * response to the * client or not */ boolean returnInnerError(HttpHeaders httpHeaders, UriInfo uriInfo, ODataProducerException exception); diff --git a/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtensions.java b/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtensions.java index bc91d88..056e9af 100644 --- a/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtensions.java +++ b/odata-core/src/main/java/org/odata4j/producer/ErrorResponseExtensions.java @@ -1,12 +1,13 @@ package org.odata4j.producer; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.exceptions.ODataProducerException; /** - * This class provides implementations of the {@link ErrorResponseExtension} interface for common + * This class provides implementations of the {@link ErrorResponseExtension} + * interface for common * use cases. */ public class ErrorResponseExtensions { @@ -23,7 +24,8 @@ public boolean returnInnerError(HttpHeaders httpHeaders, UriInfo uriInfo, ODataP } /** - * Default system property and query parameter that drives whether or not inner errors are returned. + * Default system property and query parameter that drives whether or not inner + * errors are returned. * * @see ErrorResponseExtensions#returnInnerErrorsBasedOnDefaultSystemProperty * @see ErrorResponseExtensions#returnInnerErrorsBasedOnDefaultQueryParameter @@ -42,7 +44,7 @@ public static final ErrorResponseExtension returnInnerErrorsBasedOnDefaultSystem /** * Returns inner errors when a system property is set to {@code true}. * - * @param propertyName the system property key + * @param propertyName the system property key */ public static final ErrorResponseExtension returnInnerErrorsBasedOnSystemProperty(final String propertyName) { return new ErrorResponseExtension() { @@ -64,7 +66,7 @@ public static final ErrorResponseExtension returnInnerErrorsBasedOnDefaultQueryP /** * Returns inner errors when a custom query parameter is set to {@code true}. * - * @param queryParameterName the custom parameter key + * @param queryParameterName the custom parameter key */ public static final ErrorResponseExtension returnInnerErrorsBasedOnQueryParameter(final String queryParameterName) { return new ErrorResponseExtension() { diff --git a/odata-core/src/main/java/org/odata4j/producer/ODataContextImpl.java b/odata-core/src/main/java/org/odata4j/producer/ODataContextImpl.java index b9e308f..2417bda 100644 --- a/odata-core/src/main/java/org/odata4j/producer/ODataContextImpl.java +++ b/odata-core/src/main/java/org/odata4j/producer/ODataContextImpl.java @@ -4,14 +4,15 @@ import java.util.Map; import java.util.Map.Entry; -import javax.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.HttpHeaders; /** * An implementation of ODataContext */ public class ODataContextImpl implements ODataContext { - private ODataContextImpl() {} + private ODataContextImpl() { + } @Override public T getContextAspect(Class contextClass) { @@ -33,17 +34,18 @@ public static ODataContextBuilder builder() { } public static class ODataContextBuilder { - protected ODataContextBuilder() {} + protected ODataContextBuilder() { + } public ODataContextBuilder aspect(Object aspect) { // in Jersy, ContainerRequest implements a bunch of interfaces ( // HttpRequestContext, Traceable, HttpHeaders, Reqeust, SecurityContext). - // JohnS wants to avoid coupling with javax.ws.rs things whenever - // possible. So, we wrap things we provide wrappers for (and also expose - // them as their native things). I'm not really sure of the value - // of this...isn't odata4j intrinsically linked to javax.ws.rs already? + // JohnS wants to avoid coupling with jakarta.ws.rs things whenever + // possible. So, we wrap things we provide wrappers for (and also expose + // them as their native things). I'm not really sure of the value + // of this...isn't odata4j intrinsically linked to jakarta.ws.rs already? // it's not like we are going to swap that out... if (HttpHeaders.class.isAssignableFrom(aspect.getClass())) { diff --git a/odata-core/src/main/java/org/odata4j/producer/ODataHeadersImpl.java b/odata-core/src/main/java/org/odata4j/producer/ODataHeadersImpl.java index c6daf85..f069eec 100644 --- a/odata-core/src/main/java/org/odata4j/producer/ODataHeadersImpl.java +++ b/odata-core/src/main/java/org/odata4j/producer/ODataHeadersImpl.java @@ -3,10 +3,10 @@ import java.util.List; import java.util.Locale; -import javax.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.HttpHeaders; /** - * An (probably the only ever) implementation of ODataHeadersContext + * An (probably the only ever) implementation of ODataHeadersContext * */ public class ODataHeadersImpl implements ODataHeadersContext { diff --git a/odata-core/src/main/java/org/odata4j/producer/OMediaLinkExtension.java b/odata-core/src/main/java/org/odata4j/producer/OMediaLinkExtension.java index 055b2c8..e8bb041 100644 --- a/odata-core/src/main/java/org/odata4j/producer/OMediaLinkExtension.java +++ b/odata-core/src/main/java/org/odata4j/producer/OMediaLinkExtension.java @@ -3,7 +3,7 @@ import java.io.InputStream; import java.io.OutputStream; -import javax.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.HttpHeaders; import org.odata4j.core.OEntity; import org.odata4j.core.OEntityKey; @@ -11,7 +11,8 @@ import org.odata4j.edm.EdmEntitySet; /** - * An optional extension that a producer can expose to work with Media Link Entries. + * An optional extension that a producer can expose to work with Media Link + * Entries. */ public interface OMediaLinkExtension extends OExtension { @@ -19,45 +20,48 @@ public interface OMediaLinkExtension extends OExtension { * Gets an InputStream that streams the bytes of the media resource associated * with the given media link entry entity. * - * @param mle the media link entry entity + * @param mle the media link entry entity * @param etag for future extension - * @param query additional request information + * @param query additional request information * @return InputStream for the media resource */ - InputStream getInputStreamForMediaLinkEntry(ODataContext odataContext, OEntity mle, String etag, EntityQueryInfo query); + InputStream getInputStreamForMediaLinkEntry(ODataContext odataContext, OEntity mle, String etag, + EntityQueryInfo query); /** * Gets an OutputStream for the purpose of creating a media resource. * - * @param mle the media link entry entity + * @param mle the media link entry entity * @param etag for future extension - * @param query additional request information + * @param query additional request information * @return stream to write the resource */ - OutputStream getOutputStreamForMediaLinkEntryCreate(ODataContext odataContext, OEntity mle, String etag, QueryInfo query); + OutputStream getOutputStreamForMediaLinkEntryCreate(ODataContext odataContext, OEntity mle, String etag, + QueryInfo query); /** * Gets an OutputStream for the purpose of updating an existing media resource. * - * @param mle the media link entry entity + * @param mle the media link entry entity * @param etag for future extension - * @param query additional request information + * @param query additional request information * @return stream to update the resource */ - OutputStream getOutputStreamForMediaLinkEntryUpdate(ODataContext odataContext, OEntity mle, String etag, QueryInfo query); + OutputStream getOutputStreamForMediaLinkEntryUpdate(ODataContext odataContext, OEntity mle, String etag, + QueryInfo query); /** * Deletes the media resource defined by the given media link entry entity. * - * @param mle an existing media link entry - * @param query additional request information + * @param mle an existing media link entry + * @param query additional request information */ void deleteStream(ODataContext odataContext, OEntity mle, QueryInfo query); /** * Gets the mime content type for the given media link entry entity. * - * @param mle an existing media link entry + * @param mle an existing media link entry * @return the mime content type */ String getMediaLinkContentType(ODataContext taContext, OEntity mle); @@ -65,7 +69,7 @@ public interface OMediaLinkExtension extends OExtension { /** * Gets the mime content disposition for the given media link entry entity. * - * @param mle an existing media link entry + * @param mle an existing media link entry * @return the mime content disposition */ String getMediaLinkContentDisposition(ODataContext odataContext, OEntity mle); @@ -73,8 +77,9 @@ public interface OMediaLinkExtension extends OExtension { /** * Creates an OEntity for a new media link entry request just received. * - * @param entitySet entity-set - * @param httpHeaders Atom protocol says the Slug header can contain additional create info. + * @param entitySet entity-set + * @param httpHeaders Atom protocol says the Slug header can contain additional + * create info. * @return the new entity */ OEntity createMediaLinkEntry(ODataContext odataContext, EdmEntitySet entitySet, HttpHeaders httpHeaders); @@ -82,26 +87,28 @@ public interface OMediaLinkExtension extends OExtension { /** * Gets an OEntity for an existing media link entry with the given key. * - * @param entitySet entity-set - * @param key entity key - * @param httpHeaders Atom protocol says the Slug header can contain additional create info. + * @param entitySet entity-set + * @param key entity key + * @param httpHeaders Atom protocol says the Slug header can contain additional + * create info. * @return the entity */ - OEntity getMediaLinkEntryForUpdateOrDelete(ODataContext odataContext, EdmEntitySet entitySet, OEntityKey key, HttpHeaders httpHeaders); + OEntity getMediaLinkEntryForUpdateOrDelete(ODataContext odataContext, EdmEntitySet entitySet, OEntityKey key, + HttpHeaders httpHeaders); /** * Updates an OEntity for an existing media link entry. * * After a create or update of a media resource, more information may be * available about the media link entity that was created before the media - * resource bits were processed. updateMediaLinkEntry will be called after the + * resource bits were processed. updateMediaLinkEntry will be called after the * media resource bits have been written to outStream and outStream has been * closed. * * Note: this is only necessary because OEntity is immutable * - * @param mle an existing media link entry - * @param outStream media stream + * @param mle an existing media link entry + * @param outStream media stream * @return an updated Media Link Entity */ OEntity updateMediaLinkEntry(ODataContext odataContext, OEntity mle, OutputStream outStream); diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/AbstractODataApplication.java b/odata-core/src/main/java/org/odata4j/producer/resources/AbstractODataApplication.java index b0cf9e4..69ea6d0 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/AbstractODataApplication.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/AbstractODataApplication.java @@ -3,13 +3,15 @@ import java.util.HashSet; import java.util.Set; -import javax.ws.rs.core.Application; +import jakarta.ws.rs.core.Application; /** * Abstract OData application. * - *

Implementers should override the {@code getClasses} method, but call - * {@code super.getClasses()} before adding container-specific resources and providers as + *

+ * Implementers should override the {@code getClasses} method, but call + * {@code super.getClasses()} before adding container-specific resources and + * providers as * required. */ public abstract class AbstractODataApplication extends Application { diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/BaseResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/BaseResource.java index 71192c0..98e4833 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/BaseResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/BaseResource.java @@ -8,11 +8,11 @@ import java.io.StringReader; import java.io.UnsupportedEncodingException; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.ContextResolver; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataVersion; @@ -34,26 +34,31 @@ public abstract class BaseResource { - protected OEntity getRequestEntity(HttpHeaders httpHeaders, UriInfo uriInfo, String payload, EdmDataServices metadata, String entitySetName, OEntityKey entityKey) { + protected OEntity getRequestEntity(HttpHeaders httpHeaders, UriInfo uriInfo, String payload, EdmDataServices metadata, + String entitySetName, OEntityKey entityKey) { // TODO validation of MaxDataServiceVersion against DataServiceVersion // see spec [ms-odata] section 1.7 - ODataVersion version = InternalUtil.getDataServiceVersion(httpHeaders.getRequestHeaders().getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); + ODataVersion version = InternalUtil + .getDataServiceVersion(httpHeaders.getRequestHeaders().getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); return convertFromString(payload, httpHeaders.getMediaType(), version, metadata, entitySetName, entityKey); } - private static OEntity convertFromString(String requestEntity, MediaType type, ODataVersion version, EdmDataServices metadata, String entitySetName, OEntityKey entityKey) throws NotAcceptableException { + private static OEntity convertFromString(String requestEntity, MediaType type, ODataVersion version, + EdmDataServices metadata, String entitySetName, OEntityKey entityKey) throws NotAcceptableException { FormatParser parser = FormatParserFactory.getParser(Entry.class, type, new Settings(version, metadata, entitySetName, entityKey, false)); Entry entry = parser.parse(new StringReader(requestEntity)); return entry.getEntity(); } - protected OEntity getRequestEntity(HttpHeaders httpHeaders, UriInfo uriInfo, InputStream payload, EdmDataServices metadata, String entitySetName, OEntityKey entityKey) throws UnsupportedEncodingException { + protected OEntity getRequestEntity(HttpHeaders httpHeaders, UriInfo uriInfo, InputStream payload, + EdmDataServices metadata, String entitySetName, OEntityKey entityKey) throws UnsupportedEncodingException { // TODO validation of MaxDataServiceVersion against DataServiceVersion // see spec [ms-odata] section 1.7 - ODataVersion version = InternalUtil.getDataServiceVersion(httpHeaders.getRequestHeaders().getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); + ODataVersion version = InternalUtil + .getDataServiceVersion(httpHeaders.getRequestHeaders().getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); FormatParser parser = FormatParserFactory.getParser(Entry.class, httpHeaders.getMediaType(), new Settings(version, metadata, entitySetName, entityKey, false)); @@ -69,7 +74,8 @@ protected OEntity getRequestEntity(HttpHeaders httpHeaders, UriInfo uriInfo, Inp } // some helpers for media link entries - protected OMediaLinkExtension getMediaLinkExtension(HttpHeaders httpHeaders, UriInfo uriInfo, EdmEntitySet entitySet, ODataProducer producer, + protected OMediaLinkExtension getMediaLinkExtension(HttpHeaders httpHeaders, UriInfo uriInfo, EdmEntitySet entitySet, + ODataProducer producer, ODataContext context) { OMediaLinkExtensions mediaLinkExtensions = producer.findExtension(OMediaLinkExtensions.class); @@ -87,7 +93,9 @@ protected OEntity createOrUpdateMediaLinkEntry(HttpHeaders httpHeaders, /* * this post has a great descriptions of the twists and turns of creating - * a media resource + media link entry: http://blogs.msdn.com/b/astoriateam/archive/2010/08/04/data-services-streaming-provider-series-implementing-a-streaming-provider-part-1.aspx + * a media resource + media link entry: + * http://blogs.msdn.com/b/astoriateam/archive/2010/08/04/data-services- + * streaming-provider-series-implementing-a-streaming-provider-part-1.aspx */ // first, the producer must support OMediaLinkExtension @@ -100,7 +108,11 @@ protected OEntity createOrUpdateMediaLinkEntry(HttpHeaders httpHeaders, // now get a stream we can write the incoming bytes into. OutputStream outStream = key == null - ? mediaLinkExtension.getOutputStreamForMediaLinkEntryCreate(context, mle, null /*etag*/, null /*QueryInfo, may get rid of this */) + ? mediaLinkExtension.getOutputStreamForMediaLinkEntryCreate(context, mle, null /* etag */, null /* + * QueryInfo, + * may get rid + * of this + */) : mediaLinkExtension.getOutputStreamForMediaLinkEntryUpdate(context, mle, null, null); // write the stream @@ -113,10 +125,11 @@ protected OEntity createOrUpdateMediaLinkEntry(HttpHeaders httpHeaders, // more info about the mle may be available now. return mediaLinkExtension.updateMediaLinkEntry(context, mle, outStream); } - - static ODataProducer getODataProducer(Providers providers) { - ContextResolver producerResolver = providers.getContextResolver(ODataProducer.class,MediaType.WILDCARD_TYPE); - return producerResolver.getContext(ODataProducer.class); - } - + + static ODataProducer getODataProducer(Providers providers) { + ContextResolver producerResolver = providers.getContextResolver(ODataProducer.class, + MediaType.WILDCARD_TYPE); + return producerResolver.getContext(ODataProducer.class); + } + } \ No newline at end of file diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/BatchBodyPart.java b/odata-core/src/main/java/org/odata4j/producer/resources/BatchBodyPart.java index 7b41128..92979aa 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/BatchBodyPart.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/BatchBodyPart.java @@ -1,8 +1,8 @@ package org.odata4j.producer.resources; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.producer.resources.ODataBatchProvider.HTTP_METHOD; diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/ClientAccessPolicyXmlResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/ClientAccessPolicyXmlResource.java index b795978..0ca5d49 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/ClientAccessPolicyXmlResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/ClientAccessPolicyXmlResource.java @@ -1,8 +1,8 @@ package org.odata4j.producer.resources; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; import org.odata4j.core.ODataConstants.Charsets; diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/CrossDomainXmlResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/CrossDomainXmlResource.java index eed87d8..b6126f5 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/CrossDomainXmlResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/CrossDomainXmlResource.java @@ -1,8 +1,8 @@ package org.odata4j.producer.resources; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; @Path("crossdomain.xml") public class CrossDomainXmlResource { diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/DefaultODataProducerProvider.java b/odata-core/src/main/java/org/odata4j/producer/resources/DefaultODataProducerProvider.java index 63aba83..feca7af 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/DefaultODataProducerProvider.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/DefaultODataProducerProvider.java @@ -3,8 +3,8 @@ import java.util.Properties; import java.util.logging.Logger; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; +import jakarta.ws.rs.ext.ContextResolver; +import jakarta.ws.rs.ext.Provider; import org.odata4j.core.Throwables; import org.odata4j.producer.ODataProducer; @@ -13,13 +13,20 @@ /** * Default OData producer provider. * - *

OData producer instances can either be set statically (method {@code setInstance}) - * or created by a factory ({@link ODataProducerFactory}) specified by the corresponding + *

+ * OData producer instances can either be set statically (method + * {@code setInstance}) + * or created by a factory ({@link ODataProducerFactory}) specified by the + * corresponding * system property (constant {@code FACTORY_PROPNAME}). * - *

To introduce an additional container-specific setting, it is required to extend - * this class and override method {@code createInstanceFromFactoryInContainerSpecificSetting}. - * Furthermore a subclass of {@link AbstractODataApplication} has to be created to make + *

+ * To introduce an additional container-specific setting, it is required to + * extend + * this class and override method + * {@code createInstanceFromFactoryInContainerSpecificSetting}. + * Furthermore a subclass of {@link AbstractODataApplication} has to be created + * to make * the new provider available to the JAX-RS runtime. */ @Provider @@ -35,7 +42,7 @@ public class DefaultODataProducerProvider implements ContextResolverThe default implementation returns {@code null}. Implementers can use the helper + *

+ * The default implementation returns {@code null}. Implementers can use the + * helper * methods {@code newProducerFromFactory} and {@code log}. * - * @return the OData producer or {@code null} if no container-specific setting exists + * @return the OData producer or {@code null} if no container-specific setting + * exists */ protected ODataProducer createInstanceFromFactoryInContainerSpecificSetting() { return null; @@ -98,11 +112,12 @@ private ODataProducer createInstanceFromFactoryInSystemProperties() { } /** - * Helper method to create an OData producer instance from a given producer factory + * Helper method to create an OData producer instance from a given producer + * factory * ({@link ODataProducerFactory}). * - * @param factoryTypeName the factory's type name (fully qualified) - * @param props the properties to use when constructing the producer + * @param factoryTypeName the factory's type name (fully qualified) + * @param props the properties to use when constructing the producer * @return the new producer */ protected final ODataProducer newProducerFromFactory(String factoryTypeName, Properties props) { @@ -119,7 +134,7 @@ protected final ODataProducer newProducerFromFactory(String factoryTypeName, Pro /** * Helper method to log an INFO message. * - * @param msg the log message + * @param msg the log message */ protected final void log(String msg) { log.info(msg); diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/EntitiesRequestResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/EntitiesRequestResource.java index 1f1bd63..7f2d1e5 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/EntitiesRequestResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/EntitiesRequestResource.java @@ -7,24 +7,24 @@ import java.util.logging.Level; import java.util.logging.Logger; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Request; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Request; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.Guid; import org.odata4j.core.ODataConstants; @@ -53,11 +53,11 @@ public class EntitiesRequestResource extends BaseResource { @POST @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, - ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) + ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) public Response createEntity( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -69,7 +69,8 @@ public Response createEntity( InputStream payload) throws Exception { // visual studio will send a soap mex request - if (entitySetName.equals("mex") && httpHeaders.getMediaType() != null && httpHeaders.getMediaType().toString().startsWith("application/soap+xml")) + if (entitySetName.equals("mex") && httpHeaders.getMediaType() != null + && httpHeaders.getMediaType().toString().startsWith("application/soap+xml")) throw new UnsupportedMediaTypeException("SOAP mex requests are not supported"); log("createEntity", "entitySetName", entitySetName); @@ -89,7 +90,8 @@ public Response createEntity( } QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build(); - return FunctionResource.callFunction(callingMethod, httpHeaders, uriInfo, securityContext, producer, entitySetName, format, callback, query); + return FunctionResource.callFunction(callingMethod, httpHeaders, uriInfo, securityContext, producer, + entitySetName, format, callback, query); } // is this a new media resource? @@ -114,7 +116,8 @@ public Response createEntity( // also on the plus side we can now parse the stream directly off the wire.... return createEntity(httpHeaders, uriInfo, securityContext, producer, entitySetName, - this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, null), odataContext); + this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, null), + odataContext); } protected Response createEntity( @@ -143,7 +146,8 @@ protected Response createEntity( .status(Status.CREATED) .location(URI.create(entryId)) .header(ODataConstants.Headers.DATA_SERVICE_VERSION, - ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + ODataConstants.DATA_SERVICE_VERSION_HEADER) + .build(); } protected Response createMediaLinkEntry( @@ -157,7 +161,8 @@ protected Response createMediaLinkEntry( log("createMediaLinkEntity", "entitySetName", entitySet.getName()); - OEntity mle = super.createOrUpdateMediaLinkEntry(httpHeaders, uriInfo, entitySet, producer, payload, null, odataContext); + OEntity mle = super.createOrUpdateMediaLinkEntry(httpHeaders, uriInfo, entitySet, producer, payload, null, + odataContext); // return the mle return createEntity(httpHeaders, @@ -192,7 +197,8 @@ public Response functionCallPut( // same set of query options as entity set queries so give them everything. QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build(); - response = FunctionResource.callFunction(ODataHttpMethod.PUT, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, query); + response = FunctionResource.callFunction(ODataHttpMethod.PUT, httpHeaders, uriInfo, securityContext, producer, + functionName, format, callback, query); } else { throw new NotFoundException(functionName); } @@ -223,7 +229,8 @@ public Response functionCallDelete( // same set of query options as entity set queries so give them everything. QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build(); - response = FunctionResource.callFunction(ODataHttpMethod.DELETE, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, query); + response = FunctionResource.callFunction(ODataHttpMethod.DELETE, httpHeaders, uriInfo, securityContext, producer, + functionName, format, callback, query); } else { throw new NotFoundException(functionName); } @@ -233,11 +240,11 @@ public Response functionCallDelete( @GET @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, - ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) + ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) public Response getEntities( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -271,20 +278,21 @@ public Response getEntities( ODataProducer producer = getODataProducer(providers); - return getEntitiesImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, false, inlineCount, top, skip, + return getEntitiesImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, false, inlineCount, top, + skip, filter, orderBy, format, callback, skipToken, expand, select); } @GET @Path("{count: [$]count}") @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, - ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.TEXT_PLAIN_CHARSET_UTF8, - ODataConstants.TEXT_PLAIN, - ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) + ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.TEXT_PLAIN_CHARSET_UTF8, + ODataConstants.TEXT_PLAIN, + ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) public Response getEntitiesCount( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -362,7 +370,8 @@ protected Response getEntitiesImpl( if (producer.getMetadata().findEdmFunctionImport(entitySetName) != null) { // functions that return collections of entities should support the // same set of query options as entity set queries so give them everything. - return FunctionResource.callFunction(ODataHttpMethod.GET, httpHeaders, uriInfo, securityContext, producer, entitySetName, format, callback, query); + return FunctionResource.callFunction(ODataHttpMethod.GET, httpHeaders, uriInfo, securityContext, producer, + entitySetName, format, callback, query); } Response response = null; @@ -378,8 +387,7 @@ protected Response getEntitiesImpl( .ok(entity, ODataConstants.TEXT_PLAIN_CHARSET_UTF8) .header(ODataConstants.Headers.DATA_SERVICE_VERSION, version.asString) .build(); - } - else { + } else { EntitiesResponse entitiesResponse = producer.getEntities(odataContext, entitySetName, query); if (entitiesResponse == null) { @@ -387,19 +395,19 @@ protected Response getEntitiesImpl( } StringWriter sw = new StringWriter(); - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - EntitiesResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + EntitiesResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, entitiesResponse); String entity = sw.toString(); // TODO remove this hack, check whether we are Version 2.0 compatible anyway ODataVersion version = MediaType.valueOf(fw.getContentType()).isCompatible(MediaType.APPLICATION_JSON_TYPE) - ? ODataVersion.V2 : ODataVersion.V2; + ? ODataVersion.V2 + : ODataVersion.V2; response = Response .ok(entity, fw.getContentType()) @@ -413,8 +421,8 @@ protected Response getEntitiesImpl( @Path("{batch: [$]batch}") @Consumes(ODataBatchProvider.MULTIPART_MIXED) @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML }) + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML }) public Response processBatch( @Context Providers providers, @Context HttpHeaders headers, @@ -457,24 +465,26 @@ public Response processBatch( Response response = null; switch (bodyPart.getHttpMethod()) { - case POST: - response = this.createEntity(httpHeaders, uriInfo, securityContext, producer, - entitySetName, - getRequestEntity(httpHeaders, uriInfo, entityString, producer.getMetadata(), entitySetName, null), odataContext); - break; - case PUT: - response = er.updateEntity(httpHeaders, uriInfo, securityContext, providers, - entitySetName, entityId, entityString, odataContext); - break; - case MERGE: - response = er.mergeEntity(httpHeaders, uriInfo, providers, securityContext, entitySetName, - entityId, entityString); - break; - case DELETE: - response = er.deleteEntity(httpHeaders, uriInfo, providers, securityContext, format, callback, entitySetName, entityId); - break; - case GET: - throw new UnsupportedOperationException("Not supported yet."); + case POST: + response = this.createEntity(httpHeaders, uriInfo, securityContext, producer, + entitySetName, + getRequestEntity(httpHeaders, uriInfo, entityString, producer.getMetadata(), entitySetName, null), + odataContext); + break; + case PUT: + response = er.updateEntity(httpHeaders, uriInfo, securityContext, providers, + entitySetName, entityId, entityString, odataContext); + break; + case MERGE: + response = er.mergeEntity(httpHeaders, uriInfo, providers, securityContext, entitySetName, + entityId, entityString); + break; + case DELETE: + response = er.deleteEntity(httpHeaders, uriInfo, providers, securityContext, format, callback, entitySetName, + entityId); + break; + case GET: + throw new UnsupportedOperationException("Not supported yet."); } batchResponse.append("\n--").append(changesetBoundary); @@ -492,7 +502,8 @@ public Response processBatch( return Response .status(Status.ACCEPTED) .type(ODataBatchProvider.MULTIPART_MIXED + ";boundary=" - + batchBoundary).header( + + batchBoundary) + .header( ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER) .entity(batchResponse.toString()).build(); diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/EntityRequestResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/EntityRequestResource.java index eb15f8e..3393add 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/EntityRequestResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/EntityRequestResource.java @@ -6,20 +6,20 @@ import java.io.StringWriter; import java.util.logging.Logger; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataHttpMethod; @@ -46,7 +46,7 @@ public class EntityRequestResource extends BaseResource { @PUT public Response updateEntity(@Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, - @Context Providers providers, + @Context Providers providers, @Context SecurityContext securityContext, @PathParam("entitySetName") String entitySetName, @PathParam("id") String id, @@ -76,22 +76,25 @@ public Response updateEntity(@Context HttpHeaders httpHeaders, @Context UriInfo if (Boolean.TRUE.equals(entitySet.getType().getHasStream())) { // getHasStream can return null // yes it is! - return updateMediaLinkEntry(httpHeaders, uriInfo, producer, entitySet, payload, OEntityKey.parse(id), odataContext); + return updateMediaLinkEntry(httpHeaders, uriInfo, producer, entitySet, payload, OEntityKey.parse(id), + odataContext); } - OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, OEntityKey.parse(id)); + OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, + OEntityKey.parse(id)); producer.updateEntity(odataContext, entitySetName, entity); - return Response.noContent().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.noContent() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } - /** * Updates an entity given a String payload. - * Note: currently this exists because EntitiesRequestResource processBatch needs - * a version with a String payload. It may be possible (desirable?) to - * re-write batch handling completely such that it streamed individual batch - * items instead of loading the entire batch payload into memory and then - * processing the batch items. + * Note: currently this exists because EntitiesRequestResource processBatch + * needs + * a version with a String payload. It may be possible (desirable?) to + * re-write batch handling completely such that it streamed individual batch + * items instead of loading the entire batch payload into memory and then + * processing the batch items. */ protected Response updateEntity(HttpHeaders httpHeaders, UriInfo uriInfo, SecurityContext securityContext, @Context Providers providers, @@ -117,19 +120,23 @@ protected Response updateEntity(HttpHeaders httpHeaders, UriInfo uriInfo, Securi // yes it is! ByteArrayInputStream inStream = new ByteArrayInputStream(payload.getBytes()); try { - return updateMediaLinkEntry(httpHeaders, uriInfo, producer, entitySet, inStream, OEntityKey.parse(id), odataContext); + return updateMediaLinkEntry(httpHeaders, uriInfo, producer, entitySet, inStream, OEntityKey.parse(id), + odataContext); } finally { inStream.close(); } } - OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, OEntityKey.parse(id)); + OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, + OEntityKey.parse(id)); producer.updateEntity(odataContext, entitySetName, entity); - return Response.noContent().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.noContent() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } /** - * Updates the media resource found in the payload for the media link entry (mle) + * Updates the media resource found in the payload for the media link entry + * (mle) * identified by the given key. * * @return HTTP 204 No Content response if successful. @@ -139,10 +146,12 @@ protected Response updateMediaLinkEntry(HttpHeaders httpHeaders, ODataContext odataContext) throws IOException { @SuppressWarnings("unused") - OEntity mle = super.createOrUpdateMediaLinkEntry(httpHeaders, uriInfo, entitySet, producer, payload, key, odataContext); + OEntity mle = super.createOrUpdateMediaLinkEntry(httpHeaders, uriInfo, entitySet, producer, payload, key, + odataContext); // TODO: hmmh..isn't this supposed to be HTTP 204 No Content? - return Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER) + .build(); } @POST @@ -158,24 +167,30 @@ public Response mergeEntity(@Context HttpHeaders httpHeaders, @Context UriInfo u ODataProducer producer = getODataProducer(providers); OEntityKey entityKey = OEntityKey.parse(id); - ODataContext context = ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer).build(); + ODataContext context = ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer) + .build(); String method = httpHeaders.getRequestHeaders().getFirst(ODataConstants.Headers.X_HTTP_METHOD); if ("MERGE".equals(method)) { - OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, entityKey); + OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, + entityKey); producer.mergeEntity(context, entitySetName, entity); - return Response.noContent().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.noContent() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } if ("DELETE".equals(method)) { producer.deleteEntity(context, entitySetName, entityKey); - return Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.ok() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } if ("PUT".equals(method)) { - OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, OEntityKey.parse(id)); + OEntity entity = this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, + OEntityKey.parse(id)); producer.updateEntity(context, entitySetName, entity); - return Response.noContent().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.noContent() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } if (method != null) @@ -202,7 +217,8 @@ public Response deleteEntity(@Context HttpHeaders httpHeaders, @Context UriInfo if (producer.getMetadata().findEdmFunctionImport(entitySetName) != null) { // functions that return collections of entities should support the // same set of query options as entity set queries so give them everything. - return FunctionResource.callFunction(ODataHttpMethod.DELETE, httpHeaders, uriInfo, securityContext, producer, entitySetName, format, callback, null); + return FunctionResource.callFunction(ODataHttpMethod.DELETE, httpHeaders, uriInfo, securityContext, producer, + entitySetName, format, callback, null); } OEntityKey entityKey = OEntityKey.parse(id); @@ -226,26 +242,30 @@ public Response deleteEntity(@Context HttpHeaders httpHeaders, @Context UriInfo if (Boolean.TRUE.equals(entitySet.getType().getHasStream())) { // getHasStream can return null // yes it is! // first, the producer must support OMediaLinkExtension - OMediaLinkExtension mediaLinkExtension = getMediaLinkExtension(httpHeaders, uriInfo, entitySet, producer, odataContext); + OMediaLinkExtension mediaLinkExtension = getMediaLinkExtension(httpHeaders, uriInfo, entitySet, producer, + odataContext); // get a media link entry from the extension - OEntity mle = mediaLinkExtension.getMediaLinkEntryForUpdateOrDelete(odataContext, entitySet, entityKey, httpHeaders); + OEntity mle = mediaLinkExtension.getMediaLinkEntryForUpdateOrDelete(odataContext, entitySet, entityKey, + httpHeaders); mediaLinkExtension.deleteStream(odataContext, mle, null /* QueryInfo, may need to get rid of */); // TODO: hmmh..isn't this supposed to be HTTP 204 No Content? - return Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.ok() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } producer.deleteEntity(odataContext, entitySetName, entityKey); - return Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER) + .build(); } @GET @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, - ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) + ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) public Response getEntity(@Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @Context Providers providers, @@ -258,7 +278,8 @@ public Response getEntity(@Context HttpHeaders httpHeaders, @QueryParam("$select") String select) { ODataProducer producer = getODataProducer(providers); - return getEntityImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, id, format, callback, expand, select); + return getEntityImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, id, format, callback, expand, + select); } protected Response getEntityImpl(HttpHeaders httpHeaders, UriInfo uriInfo, @@ -286,18 +307,21 @@ protected Response getEntityImpl(HttpHeaders httpHeaders, UriInfo uriInfo, EntityResponse response; try { - response = producer.getEntity(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer).build(), + response = producer.getEntity( + ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer).build(), entitySetName, OEntityKey.parse(id), query); } catch (IllegalArgumentException e) { throw new BadRequestException("Illegal key " + id, e); } StringWriter sw = new StringWriter(); - FormatWriter fw = FormatWriterFactory.getFormatWriter(EntityResponse.class, httpHeaders.getAcceptableMediaTypes(), format, callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter(EntityResponse.class, + httpHeaders.getAcceptableMediaTypes(), format, callback); fw.write(uriInfo, sw, response); String entity = sw.toString(); - return Response.ok(entity, fw.getContentType()).header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.ok(entity, fw.getContentType()) + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } @Path("{first: \\$}links/{targetNavProp:.+?}{targetId: (\\(.+?\\))?}") @@ -309,7 +333,8 @@ public LinksRequestResource getLinks( OEntityKey targetEntityKey = targetId == null || targetId.isEmpty() ? null : OEntityKey.parse(targetId); - return new LinksRequestResource(OEntityIds.create(entitySetName, OEntityKey.parse(id)), targetNavProp, targetEntityKey); + return new LinksRequestResource(OEntityIds.create(entitySetName, OEntityKey.parse(id)), targetNavProp, + targetEntityKey); } @Path("{first: \\$}value") diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/ExceptionMappingProvider.java b/odata-core/src/main/java/org/odata4j/producer/resources/ExceptionMappingProvider.java index b3de5d1..5c2edde 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/ExceptionMappingProvider.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/ExceptionMappingProvider.java @@ -2,16 +2,16 @@ import java.io.StringWriter; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.ContextResolver; +import jakarta.ws.rs.ext.ExceptionMapper; +import jakarta.ws.rs.ext.Provider; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.ODataConstants; import org.odata4j.core.OError; @@ -26,8 +26,10 @@ import org.odata4j.producer.Responses; /** - * Provider for correctly formatted server errors. Every {@link RuntimeException} that - * is not already an {@link ODataProducerException} is wrapped into a {@link ServerErrorException} + * Provider for correctly formatted server errors. Every + * {@link RuntimeException} that + * is not already an {@link ODataProducerException} is wrapped into a + * {@link ServerErrorException} * (resulting in an HTTP {@link Status#INTERNAL_SERVER_ERROR}). * * @see ErrorResponseExtension @@ -35,9 +37,9 @@ @Provider public class ExceptionMappingProvider implements ExceptionMapper { - @Context + @Context protected Providers providers; - + @Context protected UriInfo uriInfo; @Context @@ -50,10 +52,13 @@ public Response toResponse(RuntimeException e) { else exception = new ServerErrorException(e); - ErrorResponseExtension errorResponseExtension = getODataProducer(providers).findExtension(ErrorResponseExtension.class); - boolean includeInnerError = errorResponseExtension != null && errorResponseExtension.returnInnerError(httpHeaders, uriInfo, exception); + ErrorResponseExtension errorResponseExtension = getODataProducer(providers) + .findExtension(ErrorResponseExtension.class); + boolean includeInnerError = errorResponseExtension != null + && errorResponseExtension.returnInnerError(httpHeaders, uriInfo, exception); - FormatWriter fw = FormatWriterFactory.getFormatWriter(ErrorResponse.class, httpHeaders.getAcceptableMediaTypes(), + FormatWriter fw = FormatWriterFactory.getFormatWriter(ErrorResponse.class, + httpHeaders.getAcceptableMediaTypes(), getFormatParameter(), getCallbackParameter()); StringWriter sw = new StringWriter(); fw.write(uriInfo, sw, getErrorResponse(exception, includeInnerError)); @@ -79,10 +84,11 @@ private String getFormatParameter() { private String getCallbackParameter() { return uriInfo.getQueryParameters().getFirst("$callback"); } - + static ODataProducer getODataProducer(Providers providers) { - ContextResolver producerResolver = providers.getContextResolver(ODataProducer.class,MediaType.WILDCARD_TYPE); + ContextResolver producerResolver = providers.getContextResolver(ODataProducer.class, + MediaType.WILDCARD_TYPE); return producerResolver.getContext(ODataProducer.class); } - + } diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/FunctionResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/FunctionResource.java index d1214b9..fe3a37b 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/FunctionResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/FunctionResource.java @@ -6,11 +6,11 @@ import java.util.Iterator; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataHttpMethod; @@ -40,16 +40,18 @@ /** * Handles function calls. * - *

Unfortunately the OData URI scheme makes it + *

+ * Unfortunately the OData URI scheme makes it * impossible to differentiate a function call "resource" from an EntitySet. - * So, we hack: EntitiesRequestResource delegates to this class if it determines + * So, we hack: EntitiesRequestResource delegates to this class if it determines * that a function is being referenced. * - *

    TODO: - *
  • function parameter facets (required, value ranges, etc). For now, all - * validation is up to the function handler in the producer. - *
  • non-simple function parameter types - *
  • make sure this works for GET and POST + *
      + * TODO: + *
    • function parameter facets (required, value ranges, etc). For now, all + * validation is up to the function handler in the producer. + *
    • non-simple function parameter types + *
    • make sure this works for GET and POST */ public class FunctionResource extends BaseResource { @@ -83,7 +85,8 @@ public static Response callFunction( } } - BaseResponse response = producer.callFunction(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer).build(), + BaseResponse response = producer.callFunction( + ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer).build(), function, getFunctionParameters(function, queryInfo.customOptions), queryInfo); if (response == null) { @@ -97,12 +100,11 @@ public static Response callFunction( // hmmh...we are missing an abstraction somewhere.. if (response instanceof ComplexObjectResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - ComplexObjectResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + ComplexObjectResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (ComplexObjectResponse) response); fwBase = fw; @@ -117,7 +119,7 @@ public static Response callFunction( callback); // collection of entities. - // Does anyone else see this in the v2 spec? I sure don't. This seems + // Does anyone else see this in the v2 spec? I sure don't. This seems // reasonable though given that inlinecount and skip tokens might be included... ArrayList entities = new ArrayList(collectionResponse.getCollection().size()); Iterator iter = collectionResponse.getCollection().iterator(); @@ -150,32 +152,29 @@ public static Response callFunction( fw.write(uriInfo, sw, (EntitiesResponse) response); fwBase = fw; } else if (response instanceof PropertyResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - PropertyResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + PropertyResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (PropertyResponse) response); fwBase = fw; } else if (response instanceof SimpleResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - SimpleResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + SimpleResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (SimpleResponse) response); fwBase = fw; } else if (response instanceof EntityResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - EntityResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + EntityResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (EntityResponse) response); fwBase = fw; @@ -194,10 +193,11 @@ public static Response callFunction( * Takes a Map filled with the request URIs custom parameters and * turns them into a map of strongly-typed OFunctionParameter objects. * - * @param function the function being called - * @param opts request URI custom parameters + * @param function the function being called + * @param opts request URI custom parameters */ - private static Map getFunctionParameters(EdmFunctionImport function, Map opts) { + private static Map getFunctionParameters(EdmFunctionImport function, + Map opts) { Map m = new HashMap(); for (EdmFunctionParameter p : function.getParameters()) { String val = opts.get(p.getName()); diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/HeaderMap.java b/odata-core/src/main/java/org/odata4j/producer/resources/HeaderMap.java index 589ec0b..4b7ecc5 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/HeaderMap.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/HeaderMap.java @@ -5,12 +5,13 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.MultivaluedMap; /** * A {@link MultivaluedMap} with String keys and values backed by a HashMap. * - * Although keys are stored case-sensitive, all (internal) comparisons are done case-insensitive. + * Although keys are stored case-sensitive, all (internal) comparisons are done + * case-insensitive. * I.e. {@code get("key")} and {@code get("KEY")} return the same values. */ public class HeaderMap extends HashMap> implements MultivaluedMap { @@ -41,6 +42,37 @@ public String getFirst(String key) { return values.get(0); } + @Override + public void addFirst(String key, String value) { + List values = this.get(key); + if (values == null) + values = new ArrayList(); + values.add(0, value); + this.put(key, values); + } + + @Override + public boolean equalsIgnoreValueOrder(MultivaluedMap otherMap) { + if (this == otherMap) { + return true; + } + if (!keySet().equals(otherMap.keySet())) { + return false; + } + for (Entry> e : entrySet()) { + List olist = otherMap.get(e.getKey()); + if (e.getValue().size() != olist.size()) { + return false; + } + for (String v : e.getValue()) { + if (!olist.contains(v)) { + return false; + } + } + } + return true; + } + @Override public boolean containsKey(Object key) { for (String k : this.keySet()) @@ -79,57 +111,17 @@ public List remove(Object key) { } @Override - public void addAll(String key, String... newValues) - { - for (String value : newValues) - { - add(key, value); - } - } - - @Override - public void addAll(String key, List valueList) - { - for (String value : valueList) - { - add(key, value); - } + public void addAll(String key, String... newValues) { + for (String value : newValues) { + add(key, value); + } } - + @Override - public void addFirst(String key, String value) - { - List list = get(key); - if (list == null) - { - add(key, value); - return; - } - else - { - list.add(0, value); - } - } - - @Override - public boolean equalsIgnoreValueOrder(MultivaluedMap omap) { - if (this == omap) { - return true; - } - if (!keySet().equals(omap.keySet())) { - return false; - } - for (Map.Entry> e : entrySet()) { - List olist = omap.get(e.getKey()); - if (e.getValue().size() != olist.size()) { - return false; - } - for (String v : e.getValue()) { - if (!olist.contains(v)) { - return false; - } - } - } - return true; + public void addAll(String key, List valueList) { + for (String value : valueList) { + add(key, value); + } } + } diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/LinksRequestResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/LinksRequestResource.java index c34be36..af0bbc4 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/LinksRequestResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/LinksRequestResource.java @@ -4,18 +4,18 @@ import java.io.StringWriter; import java.util.logging.Logger; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.ContextResolver; +import jakarta.ws.rs.ext.Providers; import org.core4j.Enumerable; import org.odata4j.core.ODataConstants; @@ -64,7 +64,8 @@ public Response createLink(@Context HttpHeaders httpHeaders, ODataProducer producer = getODataProducer(providers); OEntityId newTargetEntity = parseRequestUri(httpHeaders, uriInfo, payload); - producer.createLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp, newTargetEntity); + producer.createLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, + targetNavProp, newTargetEntity); return noContent(); } @@ -84,7 +85,8 @@ public Response updateLink(@Context HttpHeaders httpHeaders, ODataProducer producer = getODataProducer(providers); OEntityId newTargetEntity = parseRequestUri(httpHeaders, uriInfo, payload); - producer.updateLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp, targetEntityKey, newTargetEntity); + producer.updateLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, + targetNavProp, targetEntityKey, newTargetEntity); return noContent(); } @@ -95,7 +97,8 @@ private OEntityId parseRequestUri(HttpHeaders httpHeaders, UriInfo uriInfo, Stri } private Response noContent() { - return Response.noContent().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.noContent() + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } @DELETE @@ -112,7 +115,8 @@ public Response deleteLink(@Context HttpHeaders httpHeaders, ODataProducer producer = getODataProducer(providers); - producer.deleteLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp, targetEntityKey); + producer.deleteLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, + targetNavProp, targetEntityKey); return noContent(); } @@ -133,14 +137,16 @@ public Response getLinks(@Context HttpHeaders httpHeaders, ODataProducer producer = getODataProducer(providers); - EntityIdResponse response = producer.getLinks(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp); + EntityIdResponse response = producer.getLinks( + ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp); StringWriter sw = new StringWriter(); String serviceRootUri = uriInfo.getBaseUri().toString(); String contentType; if (response.getMultiplicity() == EdmMultiplicity.MANY) { SingleLinks links = SingleLinks.create(serviceRootUri, response.getEntities()); - FormatWriter fw = FormatWriterFactory.getFormatWriter(SingleLinks.class, httpHeaders.getAcceptableMediaTypes(), format, callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter(SingleLinks.class, + httpHeaders.getAcceptableMediaTypes(), format, callback); fw.write(uriInfo, sw, links); contentType = fw.getContentType(); } else { @@ -149,14 +155,16 @@ public Response getLinks(@Context HttpHeaders httpHeaders, throw new NotFoundException(); SingleLink link = SingleLinks.create(serviceRootUri, entityId); - FormatWriter fw = FormatWriterFactory.getFormatWriter(SingleLink.class, httpHeaders.getAcceptableMediaTypes(), format, callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter(SingleLink.class, + httpHeaders.getAcceptableMediaTypes(), format, callback); fw.write(uriInfo, sw, link); contentType = fw.getContentType(); } String entity = sw.toString(); - return Response.ok(entity, contentType).header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); + return Response.ok(entity, contentType) + .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER).build(); } } diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/MetadataResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/MetadataResource.java index 489e2e4..9d1db10 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/MetadataResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/MetadataResource.java @@ -2,19 +2,19 @@ import java.io.StringWriter; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.ContextResolver; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.ODataConstants; import org.odata4j.edm.EdmDataServices; @@ -27,12 +27,13 @@ @Path("{first: \\$}metadata") public class MetadataResource { - private static final MediaType APPLICATION_ATOMSVC_XML_MEDIATYPE = MediaType.valueOf(ODataConstants.APPLICATION_ATOMSVC_XML); + private static final MediaType APPLICATION_ATOMSVC_XML_MEDIATYPE = MediaType + .valueOf(ODataConstants.APPLICATION_ATOMSVC_XML); @GET @Produces({ ODataConstants.APPLICATION_XML_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOMSVC_XML_CHARSET_UTF8, - ODataConstants.APPLICATION_XML }) + ODataConstants.APPLICATION_ATOMSVC_XML_CHARSET_UTF8, + ODataConstants.APPLICATION_XML }) public Response getMetadata( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -41,7 +42,8 @@ public Response getMetadata( ODataProducer producer = BaseResource.getODataProducer(providers); - // a request for media type atomsvc+xml means give me the service document of the metadata producer + // a request for media type atomsvc+xml means give me the service document of + // the metadata producer if ("atomsvc".equals(format) || isAtomSvcRequest(httpHeaders)) { MetadataProducer metadataProducer = producer.getMetadataProducer(); if (metadataProducer == null) { @@ -73,10 +75,10 @@ private boolean isAtomSvcRequest(HttpHeaders h) { @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) - + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) + public Response getMetadataEntities( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -103,7 +105,8 @@ public Response getMetadataEntities( } EntitiesRequestResource r = new EntitiesRequestResource(); - return r.getEntitiesImpl(httpHeaders, uriInfo, securityContext, metadataProducer, entitySetName, false, inlineCount, top, skip, filter, orderBy, format, callback, skipToken, expand, select); + return r.getEntitiesImpl(httpHeaders, uriInfo, securityContext, metadataProducer, entitySetName, false, inlineCount, + top, skip, filter, orderBy, format, callback, skipToken, expand, select); } @GET @@ -111,10 +114,10 @@ public Response getMetadataEntities( @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) - + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) + public Response getMetadataEntity( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -135,7 +138,8 @@ public Response getMetadataEntity( } EntityRequestResource r = new EntityRequestResource(); - return r.getEntityImpl(httpHeaders, uriInfo, securityContext, metadataProducer, entitySetName, id, format, callback, expand, select); + return r.getEntityImpl(httpHeaders, uriInfo, securityContext, metadataProducer, entitySetName, id, format, callback, + expand, select); } private static NotImplementedException newMetadataNotImplementedException() { diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/ODataBatchProvider.java b/odata-core/src/main/java/org/odata4j/producer/resources/ODataBatchProvider.java index 26991ee..e6102f4 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/ODataBatchProvider.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/ODataBatchProvider.java @@ -10,17 +10,17 @@ import java.util.ArrayList; import java.util.List; -import javax.ws.rs.Consumes; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.MessageBodyReader; -import javax.ws.rs.ext.Provider; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.WebApplicationException; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.MessageBodyReader; +import jakarta.ws.rs.ext.Provider; @Provider @Consumes(ODataBatchProvider.MULTIPART_MIXED) diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/OptionsQueryParser.java b/odata-core/src/main/java/org/odata4j/producer/resources/OptionsQueryParser.java index f52aefd..4183d71 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/OptionsQueryParser.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/OptionsQueryParser.java @@ -4,7 +4,7 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.UriInfo; import org.odata4j.expression.BoolCommonExpression; import org.odata4j.expression.CommonExpression; diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/PropertyRequestResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/PropertyRequestResource.java index 716cf91..1387037 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/PropertyRequestResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/PropertyRequestResource.java @@ -4,21 +4,21 @@ import java.net.URI; import java.util.logging.Logger; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataVersion; @@ -43,12 +43,11 @@ public class PropertyRequestResource extends BaseResource { - private static final Logger log = - Logger.getLogger(PropertyRequestResource.class.getName()); + private static final Logger log = Logger.getLogger(PropertyRequestResource.class.getName()); @PUT public Response updateEntity( - @Context Providers providers, + @Context Providers providers, @PathParam("entitySetName") String entitySetName, @PathParam("id") String id, @PathParam("navProp") String navProp) { @@ -83,7 +82,8 @@ public Response mergeEntity( OEntity entity = getRequestEntity(httpHeaders, uriInfo, payload, metadata, ees.getName(), OEntityKey.parse(id)); // execute the create - EntityResponse response = producer.createEntity(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), + EntityResponse response = producer.createEntity( + ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), entitySetName, OEntityKey.parse(id), navProp, entity); if (response == null) { @@ -115,7 +115,7 @@ public Response mergeEntity( @DELETE public Response deleteEntity( - @Context Providers providers, + @Context Providers providers, @PathParam("entitySetName") String entitySetName, @PathParam("id") String id, @PathParam("navProp") String navProp) { @@ -124,11 +124,11 @@ public Response deleteEntity( @GET @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, - ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, - ODataConstants.APPLICATION_ATOM_XML, - ODataConstants.APPLICATION_XML, - ODataConstants.APPLICATION_JAVASCRIPT }) + ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_ATOM_XML, + ODataConstants.APPLICATION_XML, + ODataConstants.APPLICATION_JAVASCRIPT }) public Response getNavProperty( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -188,8 +188,7 @@ public Response getNavProperty( .ok(entity, ODataConstants.TEXT_PLAIN_CHARSET_UTF8) .header(ODataConstants.Headers.DATA_SERVICE_VERSION, version.asString) .build(); - } - else { + } else { BaseResponse response = producer.getNavProperty( ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), @@ -207,47 +206,44 @@ public Response getNavProperty( StringWriter sw = new StringWriter(); FormatWriter fwBase; if (response instanceof PropertyResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - PropertyResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + PropertyResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (PropertyResponse) response); fwBase = fw; } else if (response instanceof RawResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - RawResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); - - fw.write(uriInfo, sw, (RawResponse) response); - fwBase = fw; + FormatWriter fw = FormatWriterFactory.getFormatWriter( + RawResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); + + fw.write(uriInfo, sw, (RawResponse) response); + fwBase = fw; } else if (response instanceof EntityResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - EntityResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + EntityResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (EntityResponse) response); fwBase = fw; } else if (response instanceof EntitiesResponse) { - FormatWriter fw = - FormatWriterFactory.getFormatWriter( - EntitiesResponse.class, - httpHeaders.getAcceptableMediaTypes(), - format, - callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter( + EntitiesResponse.class, + httpHeaders.getAcceptableMediaTypes(), + format, + callback); fw.write(uriInfo, sw, (EntitiesResponse) response); fwBase = fw; // TODO remove this hack, check whether we are Version 2.0 compatible anyway // the JsonWriter writes feed currently always as Version 2.0 version = MediaType.valueOf(fw.getContentType()).isCompatible(MediaType.APPLICATION_JSON_TYPE) - ? ODataVersion.V2 : ODataVersion.V2; + ? ODataVersion.V2 + : ODataVersion.V2; } else { throw new NotImplementedException("Unknown BaseResponse type: " + response.getClass().getName()); } diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/RootApplication.java b/odata-core/src/main/java/org/odata4j/producer/resources/RootApplication.java index 32507b2..de4541f 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/RootApplication.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/RootApplication.java @@ -3,10 +3,11 @@ import java.util.HashSet; import java.util.Set; -import javax.ws.rs.core.Application; +import jakarta.ws.rs.core.Application; /** - * Root application containing resources for cross domain and client access policies. + * Root application containing resources for cross domain and client access + * policies. */ public class RootApplication extends Application { diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/ServiceDocumentResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/ServiceDocumentResource.java index 4ee24ef..bfe7ec0 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/ServiceDocumentResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/ServiceDocumentResource.java @@ -2,15 +2,15 @@ import java.io.StringWriter; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.ODataConstants; import org.odata4j.edm.EdmDataServices; @@ -22,7 +22,8 @@ public class ServiceDocumentResource { @GET - @Produces({ ODataConstants.APPLICATION_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_XML }) + @Produces({ ODataConstants.APPLICATION_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, + ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_XML }) public Response getServiceDocument( @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo, @@ -35,7 +36,8 @@ public Response getServiceDocument( EdmDataServices metadata = producer.getMetadata(); StringWriter w = new StringWriter(); - FormatWriter fw = FormatWriterFactory.getFormatWriter(EdmDataServices.class, httpHeaders.getAcceptableMediaTypes(), format, callback); + FormatWriter fw = FormatWriterFactory.getFormatWriter(EdmDataServices.class, + httpHeaders.getAcceptableMediaTypes(), format, callback); fw.write(uriInfo, w, metadata); return Response.ok(w.toString(), fw.getContentType()) diff --git a/odata-core/src/main/java/org/odata4j/producer/resources/ValueRequestResource.java b/odata-core/src/main/java/org/odata4j/producer/resources/ValueRequestResource.java index 8635519..0a1e27b 100644 --- a/odata-core/src/main/java/org/odata4j/producer/resources/ValueRequestResource.java +++ b/odata-core/src/main/java/org/odata4j/producer/resources/ValueRequestResource.java @@ -2,15 +2,15 @@ import java.io.InputStream; -import javax.ws.rs.GET; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.Providers; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.UriInfo; +import jakarta.ws.rs.ext.Providers; import org.odata4j.core.OEntityKey; import org.odata4j.edm.EdmEntitySet; @@ -58,19 +58,23 @@ public Response get( throw new NotFoundException(); } - protected Response getStreamResponse(HttpHeaders httpHeaders, UriInfo uriInfo, ODataProducer producer, EdmEntitySet entitySet, String entityId, EntityQueryInfo queryInfo, + protected Response getStreamResponse(HttpHeaders httpHeaders, UriInfo uriInfo, ODataProducer producer, + EdmEntitySet entitySet, String entityId, EntityQueryInfo queryInfo, SecurityContext securityContext, ODataContext odataContext) { - OMediaLinkExtension mediaLinkExtension = this.getMediaLinkExtension(httpHeaders, uriInfo, entitySet, producer, odataContext); + OMediaLinkExtension mediaLinkExtension = this.getMediaLinkExtension(httpHeaders, uriInfo, entitySet, producer, + odataContext); if (mediaLinkExtension == null) throw new NotImplementedException(); EntityResponse entityResponse = producer.getEntity(odataContext, entitySet.getName(), OEntityKey.parse(entityId), queryInfo); - InputStream entityStream = mediaLinkExtension.getInputStreamForMediaLinkEntry(odataContext, entityResponse.getEntity(), null, queryInfo); + InputStream entityStream = mediaLinkExtension.getInputStreamForMediaLinkEntry(odataContext, + entityResponse.getEntity(), null, queryInfo); String contentType = mediaLinkExtension.getMediaLinkContentType(odataContext, entityResponse.getEntity()); - String contentDisposition = mediaLinkExtension.getMediaLinkContentDisposition(odataContext, entityResponse.getEntity()); + String contentDisposition = mediaLinkExtension.getMediaLinkContentDisposition(odataContext, + entityResponse.getEntity()); return Response.ok(entityStream, contentType).header("Content-Disposition", contentDisposition).build(); } diff --git a/odata-core/src/main/java/org/odata4j/producer/server/ODataServer.java b/odata-core/src/main/java/org/odata4j/producer/server/ODataServer.java index 4eea417..651587e 100644 --- a/odata-core/src/main/java/org/odata4j/producer/server/ODataServer.java +++ b/odata-core/src/main/java/org/odata4j/producer/server/ODataServer.java @@ -1,6 +1,6 @@ package org.odata4j.producer.server; -import javax.ws.rs.core.Application; +import jakarta.ws.rs.core.Application; import org.odata4j.producer.resources.AbstractODataApplication; import org.odata4j.producer.resources.DefaultODataApplication; @@ -28,7 +28,7 @@ public interface ODataServer { /** * Sets the OData application. * - * @param odataApp the OData application class + * @param odataApp the OData application class * @return this server * @see AbstractODataApplication * @see DefaultODataApplication @@ -38,7 +38,7 @@ public interface ODataServer { /** * Sets the root application. * - * @param rootApp the root application class + * @param rootApp the root application class * @return this server * @see RootApplication */ diff --git a/odata-core/src/main/java/org/odata4j/stax2/staximpl/StaxXMLWriter2.java b/odata-core/src/main/java/org/odata4j/stax2/staximpl/StaxXMLWriter2.java index 1d420b7..73ca1e9 100644 --- a/odata-core/src/main/java/org/odata4j/stax2/staximpl/StaxXMLWriter2.java +++ b/odata-core/src/main/java/org/odata4j/stax2/staximpl/StaxXMLWriter2.java @@ -8,6 +8,7 @@ import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.XMLEvent; @@ -65,7 +66,7 @@ public void startElement(QName2 qname) { public void startElement(QName2 qname, String xmlns) { // writer.setDefaultNamespace("http://www.example.com/ns1"); try { - Iterator nsIterator = null; + Iterator nsIterator = null; if (xmlns != null) { nsIterator = Enumerable.create(eventFactory.createNamespace(xmlns)).iterator(); } diff --git a/odata-core/src/main/java/org/odata4j/urlencoder/ConversionUtil.java b/odata-core/src/main/java/org/odata4j/urlencoder/ConversionUtil.java new file mode 100644 index 0000000..560fb75 --- /dev/null +++ b/odata-core/src/main/java/org/odata4j/urlencoder/ConversionUtil.java @@ -0,0 +1,162 @@ +package org.odata4j.urlencoder; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import jakarta.ws.rs.core.MultivaluedMap; + +import org.odata4j.producer.resources.HeaderMap; + +/** + * + * This class uses URLEncoder to Encode the String and URLDecoder to decode the + * String. + *
        + *
      1. The alphanumeric characters "a" through "z", "A" through "Z" and "0" + * through "9" remain the same.
      2. + *
      3. The special characters ".", "-", "*", and "_" remain the same.
      4. + *
      5. The space character " " is converted into a plus sign "+".
      6. + *
      7. All other characters are unsafe and are first converted into one or more + * bytes using some encoding scheme.
      8. + *
      + * Then each byte is represented by the 3-character string "%xy", where xy is + * the two-digit hexadecimal representation of the byte.
      + * The recommended encoding scheme to use is UTF-8. However, for compatibility + * reasons, if an encoding is not specified, then the default encoding of the + * platform is used. + * + * Copyright 2013 Halliburton + * + * @author Rajni Kumari + */ +public class ConversionUtil { + + /** The Constant log. */ + private static final Logger log = Logger.getLogger(ConversionUtil.class.getName()); + + /** The Constant encodingScheme. */ + private static final String encodingOrDecodingScheme = "UTF-8"; + + /** The Constant UNSUPPORTED_CHARACTER. */ + private static final Map UNSUPPORTED_CHARACTER = new HashMap(); + static { + UNSUPPORTED_CHARACTER.put("+", "%20"); + UNSUPPORTED_CHARACTER.put("%2F", "/"); + UNSUPPORTED_CHARACTER.put("%27", "'"); + UNSUPPORTED_CHARACTER.put("%3D", "="); + UNSUPPORTED_CHARACTER.put("%2C", ","); + UNSUPPORTED_CHARACTER.put("%28", "("); + UNSUPPORTED_CHARACTER.put("%29", ")"); + } + + /** + * Instantiates a new conversion util. + */ + private ConversionUtil() { + + } + + /** + * Encode string. + * + * @param stringToEncode the string to encode + * @return the string + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + public static String encodeString(String stringToEncode) { + String encodedString = null; + if (stringToEncode != null) { + try { + encodedString = ConversionUtil + .removeUnsuportedCharacter(URLEncoder.encode(stringToEncode, encodingOrDecodingScheme)); + } catch (UnsupportedEncodingException e) { + log.info(e.getMessage()); + } + } + return encodedString; + } + + /** + * Decode string. + * + * @param stringToDecode the string to decode + * @return the string + */ + public static String decodeString(String stringToDecode) { + String decodedString = null; + if (stringToDecode != null) { + try { + decodedString = URLDecoder.decode(stringToDecode, encodingOrDecodingScheme); + } catch (UnsupportedEncodingException e) { + log.warning("ConversionUtil failed to decode a string:" + stringToDecode + "\nthe error is" + + e.getMessage()); + } + } + return decodedString; + } + + /** + * Removes the unsuported character. + * + * @param encodedString the encoded string + * @return the string + */ + private static String removeUnsuportedCharacter(String encodedString) { + for (Map.Entry e : UNSUPPORTED_CHARACTER.entrySet()) { + encodedString = encodedString.replace(e.getKey(), e.getValue()); + } + return encodedString; + + } + + public static MultivaluedMap decodeQueryString(URI uri) { + + MultivaluedMap params = new HeaderMap(); + + if (uri == null) { + return params; + } + String queryString = uri.getRawQuery(); + if (queryString == null) { + return params; + } + queryString = queryString.trim(); + if (queryString.isEmpty()) { + return params; + } + + StringTokenizer st = new StringTokenizer(queryString, "&"); + while (st.hasMoreTokens()) { + String param = st.nextToken(); + param = param.trim(); + if (param.isEmpty()) { + continue; + } + + int index = param.indexOf("="); + + try { + if (index == -1) { + params.add(URLDecoder.decode(param, "UTF-8"), ""); + } else if (index > 0) { + String name = param.substring(0, index); + String value = param.substring(index + 1); + params.add(URLDecoder.decode(name, "UTF-8"), URLDecoder.decode(value, "UTF-8")); + } + } catch (UnsupportedEncodingException e) { + log.warning( + "ConversionUtil failed to decode a query string:" + param + "\nthe error is" + e.getMessage()); + + } + } + + return params; + + } +} diff --git a/odata-core/src/test/java/org/odata4j/test/unit/expressions/TypeConverterTest.java b/odata-core/src/test/java/org/odata4j/test/unit/expressions/TypeConverterTest.java index 8f31816..7cefa25 100644 --- a/odata-core/src/test/java/org/odata4j/test/unit/expressions/TypeConverterTest.java +++ b/odata-core/src/test/java/org/odata4j/test/unit/expressions/TypeConverterTest.java @@ -6,7 +6,7 @@ import java.util.Date; import java.util.Locale; -import org.junit.Assert; +import junit.framework.Assert; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; @@ -25,37 +25,51 @@ public void testTypeConverter() { @Test public void testTemporalTypes() throws ParseException { - DateFormat dateTimeParser = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.US); - DateFormat timeParser = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.US); + // Create expected dates directly to avoid locale-dependent parsing Calendar cal = Calendar.getInstance(); - Assert.assertEquals(dateTimeParser.parse("03/28/2011, 7:20:21 pm"), + // Create expected date: March 28, 2011, 7:20:21 PM + cal.set(2011, Calendar.MARCH, 28, 19, 20, 21); + cal.set(Calendar.MILLISECOND, 0); + Date expectedDateTime = cal.getTime(); + + // Create expected time: 7:20:21 PM (with epoch date 1970-01-01) + cal.set(1970, Calendar.JANUARY, 1, 19, 20, 21); + cal.set(Calendar.MILLISECOND, 0); + Date expectedTime = cal.getTime(); + + // Create expected date for 0:00:00 AM + cal.set(2011, Calendar.MARCH, 28, 0, 0, 0); + cal.set(Calendar.MILLISECOND, 0); + Date expectedDateOnly = cal.getTime(); + + Assert.assertEquals(expectedDateTime, TypeConverter.convert(new LocalDateTime(2011, 03, 28, 19, 20, 21), Date.class)); - Assert.assertEquals(timeParser.parse("7:20:21 pm"), + Assert.assertEquals(expectedTime, TypeConverter.convert(new LocalTime(19, 20, 21), Date.class)); - cal.setTime(dateTimeParser.parse("03/28/2011, 7:20:21 pm")); + cal.setTime(expectedDateTime); Assert.assertEquals(cal, TypeConverter.convert(new LocalDateTime(2011, 03, 28, 19, 20, 21), Calendar.class)); - cal.setTime(timeParser.parse("7:20:21 pm")); + cal.setTime(expectedTime); Assert.assertEquals(cal, TypeConverter.convert(new LocalTime(19, 20, 21), Calendar.class)); - Assert.assertEquals(new java.sql.Time(timeParser.parse("7:20:21 pm").getTime()), + Assert.assertEquals(new java.sql.Time(expectedTime.getTime()), TypeConverter.convert(new LocalDateTime(1970, 1, 1, 19, 20, 21), java.sql.Time.class)); - Assert.assertEquals(new java.sql.Time(timeParser.parse("7:20:21 pm").getTime()), + Assert.assertEquals(new java.sql.Time(expectedTime.getTime()), TypeConverter.convert(new LocalTime(19, 20, 21), java.sql.Time.class)); - Assert.assertEquals(new java.sql.Date(dateTimeParser.parse("03/28/2011, 0:00:00 am").getTime()), + Assert.assertEquals(new java.sql.Date(expectedDateOnly.getTime()), TypeConverter.convert(new LocalDateTime(2011, 03, 28, 0, 0), java.sql.Date.class)); - Assert.assertEquals(new java.sql.Timestamp(dateTimeParser.parse("03/28/2011, 7:20:21 pm").getTime()), + Assert.assertEquals(new java.sql.Timestamp(expectedDateTime.getTime()), TypeConverter.convert(new LocalDateTime(2011, 03, 28, 19, 20, 21), java.sql.Timestamp.class)); - Assert.assertEquals(new java.sql.Timestamp(timeParser.parse("7:20:21 pm").getTime()), + Assert.assertEquals(new java.sql.Timestamp(expectedTime.getTime()), TypeConverter.convert(new LocalTime(19, 20, 21), java.sql.Timestamp.class)); } diff --git a/odata-core/src/test/java/org/odata4j/test/unit/format/AbstractErrorFormatWriterTest.java b/odata-core/src/test/java/org/odata4j/test/unit/format/AbstractErrorFormatWriterTest.java index bf6af8c..68e284c 100644 --- a/odata-core/src/test/java/org/odata4j/test/unit/format/AbstractErrorFormatWriterTest.java +++ b/odata-core/src/test/java/org/odata4j/test/unit/format/AbstractErrorFormatWriterTest.java @@ -8,8 +8,8 @@ import java.io.StringWriter; import java.util.regex.Pattern; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriInfo; import org.junit.Before; import org.junit.Test; @@ -53,7 +53,8 @@ public void setup() throws Exception { } private void assertErrorResponse(String code, String message, String innerError) { - assertTrue(Pattern.compile(buildRegex(code, message, innerError), Pattern.DOTALL).matcher(stringWriter.toString()).matches()); + assertTrue(Pattern.compile(buildRegex(code, message, innerError), Pattern.DOTALL).matcher(stringWriter.toString()) + .matches()); } protected abstract String buildRegex(String code, String message, String innerError); @@ -66,7 +67,8 @@ public void code() throws Exception { @Test public void message() throws Exception { - formatWriter.write(uriInfoMock, stringWriter, ExceptionMappingProvider.getErrorResponse(ODATA_EXCEPTION_WITH_MESSAGE, false)); + formatWriter.write(uriInfoMock, stringWriter, + ExceptionMappingProvider.getErrorResponse(ODATA_EXCEPTION_WITH_MESSAGE, false)); assertErrorResponse(".+", MESSAGE, null); } @@ -78,7 +80,9 @@ public void innerError() throws Exception { @Test public void innerErrorWithCausedBy() throws Exception { - formatWriter.write(uriInfoMock, stringWriter, ExceptionMappingProvider.getErrorResponse(ODATA_EXCEPTION_WITH_CAUSE, true)); - assertErrorResponse(".+", ".+", ODATA_EXCEPTION_WITH_CAUSE.getClass().getName() + ".+Caused by: " + CAUSE.getClass().getName() + ".+"); + formatWriter.write(uriInfoMock, stringWriter, + ExceptionMappingProvider.getErrorResponse(ODATA_EXCEPTION_WITH_CAUSE, true)); + assertErrorResponse(".+", ".+", + ODATA_EXCEPTION_WITH_CAUSE.getClass().getName() + ".+Caused by: " + CAUSE.getClass().getName() + ".+"); } } diff --git a/odata-core/src/test/java/org/odata4j/test/unit/format/xml/AtomFeedFormatWriterTest.java b/odata-core/src/test/java/org/odata4j/test/unit/format/xml/AtomFeedFormatWriterTest.java index caf3ad2..f9977d7 100644 --- a/odata-core/src/test/java/org/odata4j/test/unit/format/xml/AtomFeedFormatWriterTest.java +++ b/odata-core/src/test/java/org/odata4j/test/unit/format/xml/AtomFeedFormatWriterTest.java @@ -15,9 +15,9 @@ import java.util.Arrays; import java.util.Collection; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriInfo; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriBuilder; +import jakarta.ws.rs.core.UriInfo; import org.core4j.Enumerable; import org.core4j.Func; @@ -148,16 +148,19 @@ public Iterable apply() { } }, "Id"); - EntitiesResponse response = p.getEntities(null, "setName", new QueryInfo(InlineCount.NONE, top, null, null, null, null, null, null, null)); + EntitiesResponse response = p.getEntities(null, "setName", + new QueryInfo(InlineCount.NONE, top, null, null, null, null, null, null, null)); formatWriter.write(uriInfoMock, stringWriter, response); String s = stringWriter.toString(); verify(uriBuilderMock, times(1)).replaceQueryParam(eq("$skiptoken"), anyString()); long newTop = top - response.getEntities().size(); if (newTop > 0) { verify(uriBuilderMock, times(1)).replaceQueryParam(eq("$top"), eq(newTop)); - // The next url in this case should be '?$top=50&$skiptoken=' and not '?$top=150&$skiptoken=' + // The next url in this case should be '?$top=50&$skiptoken=' and not + // '?$top=150&$skiptoken=' assertEquals("", s.substring(s.indexOf("", + s.substring(s.indexOf(" org.jboss jboss-parent - 17 + 29 @@ -99,18 +99,18 @@ ${project.name} verify - 1.0.0.Final 2.0.0 2.1.2 2.1 1.1.3.4a 4.12 1.1 - 1.9.0 + 2.23.0 1.8.0.10 - 1.1.5 - 2.6.0 - 7.5.3.v20111011 + 3.1.3 + 3.1.0 + 4.0.4 + 11.0.15 4.2.1 1.6.4 1.3 @@ -151,7 +151,7 @@ - + org.apache.maven.plugins maven-compiler-plugin - 1.6 - 1.6 + 1.8 + 1.8 diff --git a/test-integration/.classpath b/test-integration/.classpath index 0e334a3..892c757 100644 --- a/test-integration/.classpath +++ b/test-integration/.classpath @@ -17,6 +17,7 @@ + @@ -32,6 +33,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/test-integration/pom.xml b/test-integration/pom.xml index 96b640a..3eaef52 100644 --- a/test-integration/pom.xml +++ b/test-integration/pom.xml @@ -47,26 +47,35 @@ ${httpclient.version} - - - com.sun.jersey - jersey-core - ${jersey.version} - + + org.glassfish.jersey.core + jersey-client + ${jersey.version} + - - - com.sun.jersey - jersey-server - ${jersey.version} - + + org.glassfish.jersey.core + jersey-server + ${jersey.version} + - - - com.sun.jersey - jersey-client - ${jersey.version} - + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey.version} + + + + org.glassfish.jersey.test-framework.providers + jersey-test-framework-provider-external + ${jersey.version} + + + + org.glassfish.jersey.containers + jersey-container-servlet-core + 3.1.3 + org.slf4j @@ -88,7 +97,7 @@ org.mockito - mockito-all + mockito-core ${mockito.version} test diff --git a/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/CxfClientResponse.java b/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/CxfClientResponse.java index f0d7e07..876d47a 100644 --- a/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/CxfClientResponse.java +++ b/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/CxfClientResponse.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.MultivaluedMap; import org.apache.http.Header; import org.apache.http.HeaderElement; diff --git a/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfClient.java b/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfClient.java index 4632307..ee1018f 100644 --- a/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfClient.java +++ b/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfClient.java @@ -10,12 +10,12 @@ import java.io.UnsupportedEncodingException; import java.net.URI; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.Response.StatusType; -import javax.ws.rs.core.UriBuilder; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.Status.Family; +import jakarta.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.UriBuilder; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; @@ -61,14 +61,16 @@ */ public class ODataCxfClient extends AbstractODataClient { - private final OClientBehavior[] requiredBehaviors = new OClientBehavior[] { OClientBehaviors.methodTunneling("MERGE") }; + private final OClientBehavior[] requiredBehaviors = new OClientBehavior[] { + OClientBehaviors.methodTunneling("MERGE") }; private final OClientBehavior[] behaviors; private final HttpClient httpClient; public ODataCxfClient(FormatType type, OClientBehavior... behaviors) { super(type); - this.behaviors = Enumerable.create(requiredBehaviors).concat(Enumerable.create(behaviors)).toArray(OClientBehavior.class); + this.behaviors = Enumerable.create(requiredBehaviors).concat(Enumerable.create(behaviors)) + .toArray(OClientBehavior.class); this.httpClient = new DefaultHttpClient(); if (System.getProperties().containsKey("http.proxyHost") && System.getProperties().containsKey("http.proxyPort")) { @@ -99,7 +101,8 @@ public String requestBody(FormatType formatType, ODataClientRequest request) thr } @SuppressWarnings("unchecked") - protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, StatusType... expectedResponseStatus) throws ODataProducerException { + protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, + StatusType... expectedResponseStatus) throws ODataProducerException { UriBuilder uriBuilder = UriBuilder.fromPath(request.getUrl()); for (String key : request.getQueryParams().keySet()) uriBuilder = uriBuilder.queryParam(key, request.getQueryParams().get(key)); @@ -140,8 +143,8 @@ else if (request.getPayload() instanceof SingleLink) throw new IllegalArgumentException("Unsupported payload: " + request.getPayload()); StringWriter sw = new StringWriter(); - FormatWriter fw = (FormatWriter) - FormatWriterFactory.getFormatWriter(payloadClass, null, this.getFormatType().toString(), null); + FormatWriter fw = (FormatWriter) FormatWriterFactory.getFormatWriter(payloadClass, null, + this.getFormatType().toString(), null); fw.write(null, sw, request.getPayload()); String entityString = sw.toString(); @@ -195,7 +198,8 @@ public String getReasonPhrase() { RuntimeException exception; String textEntity = entityToString(httpResponse.getEntity()); // input stream can only be consumed once try { - // report error as ODataProducerException in case we get a well-formed OData error... + // report error as ODataProducerException in case we get a well-formed OData + // error... MediaType contentType = MediaType.valueOf(httpResponse.getEntity().getContentType().getValue()); OError error = FormatParserFactory.getParser(OError.class, contentType, null).parse(new StringReader(textEntity)); exception = ODataProducerExceptions.create(status, error); @@ -211,7 +215,8 @@ protected XMLEventReader2 toXml(ODataClientResponse response) { HttpResponse httpResponse = ((CxfClientResponse) response).getHttpResponse(); try { InputStream textEntity = httpResponse.getEntity().getContent(); - return StaxUtil.newXMLEventReader(new BOMWorkaroundReader(new InputStreamReader(textEntity, Charsets.Upper.UTF_8))); + return StaxUtil + .newXMLEventReader(new BOMWorkaroundReader(new InputStreamReader(textEntity, Charsets.Upper.UTF_8))); } catch (Exception e) { throw Throwables.propagate(e); } @@ -219,26 +224,27 @@ protected XMLEventReader2 toXml(ODataClientResponse response) { private HttpUriRequest getRequestByMethod(String method, URI uri) { switch (ODataHttpMethod.fromString(method)) { - case GET: - return new HttpGet(uri); - case PUT: - return new HttpPut(uri); - case POST: - return new HttpPost(uri); - case DELETE: - return new HttpDelete(uri); - case OPTIONS: - return new HttpOptions(uri); - case HEAD: - return new HttpHead(uri); - default: - throw new RuntimeException("Method unknown: " + method); + case GET: + return new HttpGet(uri); + case PUT: + return new HttpPut(uri); + case POST: + return new HttpPost(uri); + case DELETE: + return new HttpDelete(uri); + case OPTIONS: + return new HttpOptions(uri); + case HEAD: + return new HttpHead(uri); + default: + throw new RuntimeException("Method unknown: " + method); } } private String entityToString(HttpEntity entity) { try { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), Charsets.Upper.UTF_8)); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(entity.getContent(), Charsets.Upper.UTF_8)); StringBuilder stringBuilder = new StringBuilder(); String line = null; diff --git a/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfConsumer.java b/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfConsumer.java index f13de20..fcc2f7f 100644 --- a/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfConsumer.java +++ b/test-integration/src/main/java/org/odata4j/examples/cxf/consumer/ODataCxfConsumer.java @@ -1,6 +1,6 @@ package org.odata4j.examples.cxf.consumer; -import javax.ws.rs.ext.RuntimeDelegate; +import jakarta.ws.rs.ext.RuntimeDelegate; import org.odata4j.consumer.AbstractODataConsumer; import org.odata4j.consumer.ODataClient; @@ -8,10 +8,16 @@ import org.odata4j.consumer.behaviors.OClientBehavior; import org.odata4j.format.FormatType; +import org.glassfish.jersey.internal.AbstractRuntimeDelegate; +import org.glassfish.jersey.internal.RuntimeDelegateImpl; + /** * ODataConsumer is the client-side interface to an OData service. * - *

      Use {@link #create(String)} or one of the other static factory methods to connect to an existing OData service.

      + *

      + * Use {@link #create(String)} or one of the other static factory methods to + * connect to an existing OData service. + *

      */ public class ODataCxfConsumer extends AbstractODataConsumer { @@ -21,8 +27,8 @@ private ODataCxfConsumer(FormatType type, String serviceRootUri, OClientBehavior super(serviceRootUri); // ensure that the correct JAX-RS implementation (CXF) is loaded - if (!(RuntimeDelegate.getInstance() instanceof org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl)) - RuntimeDelegate.setInstance(new org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl()); + if (!(RuntimeDelegate.getInstance() instanceof AbstractRuntimeDelegate)) + RuntimeDelegate.setInstance(new RuntimeDelegateImpl()); this.client = new ODataCxfClient(type, behaviors); } @@ -46,7 +52,7 @@ private Builder(String serviceRootUri) { /** * Sets a preferred {@link FormatType}. Defaults to {@code FormatType.ATOM}. * - * @param formatType the format type + * @param formatType the format type * @return this builder */ public Builder setFormatType(FormatType formatType) { @@ -57,9 +63,11 @@ public Builder setFormatType(FormatType formatType) { /** * Sets one or more client behaviors. * - *

      Client behaviors transform http requests to interact with services that require custom extensions. + *

      + * Client behaviors transform http requests to interact with services that + * require custom extensions. * - * @param clientBehaviors the client behaviors + * @param clientBehaviors the client behaviors * @return this builder */ public Builder setClientBehaviors(OClientBehavior... clientBehaviors) { @@ -84,7 +92,7 @@ public ODataCxfConsumer build() { /** * Constructs a new builder for an {@link ODataCxfConsumer} object. * - * @param serviceRootUri the OData service root uri + * @param serviceRootUri the OData service root uri */ public static Builder newBuilder(String serviceRootUri) { return new Builder(serviceRootUri); @@ -93,9 +101,14 @@ public static Builder newBuilder(String serviceRootUri) { /** * Creates a new consumer for the given OData service uri. * - *

      Wrapper for {@code ODataCxfConsumer.newBuilder(serviceRootUri).build()}. + *

      + * Wrapper for {@code ODataCxfConsumer.newBuilder(serviceRootUri).build()}. * - * @param serviceRootUri the service uri

      e.g. http://services.odata.org/Northwind/Northwind.svc/

      + * @param serviceRootUri the service uri + *

      + * e.g. + * http://services.odata.org/Northwind/Northwind.svc/ + *

      * @return a new OData consumer */ public static ODataCxfConsumer create(String serviceRootUri) { diff --git a/test-integration/src/main/java/org/odata4j/examples/cxf/producer/server/ODataCxfServer.java b/test-integration/src/main/java/org/odata4j/examples/cxf/producer/server/ODataCxfServer.java index c0f6bdc..92b426a 100644 --- a/test-integration/src/main/java/org/odata4j/examples/cxf/producer/server/ODataCxfServer.java +++ b/test-integration/src/main/java/org/odata4j/examples/cxf/producer/server/ODataCxfServer.java @@ -5,8 +5,8 @@ import java.util.ArrayList; import java.util.List; -import javax.ws.rs.core.Application; -import javax.ws.rs.ext.RuntimeDelegate; +import jakarta.ws.rs.core.Application; +import jakarta.ws.rs.ext.RuntimeDelegate; import org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet; import org.core4j.Enumerable; @@ -16,6 +16,8 @@ import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; +import org.glassfish.jersey.internal.AbstractRuntimeDelegate; +import org.glassfish.jersey.internal.RuntimeDelegateImpl; import org.odata4j.core.Throwables; import org.odata4j.producer.server.ODataServer; @@ -35,11 +37,12 @@ public ODataCxfServer(String appBaseUri) { this.appBaseUri = appBaseUri; // ensure that the correct JAX-RS implementation (CXF) is loaded - if (!(RuntimeDelegate.getInstance() instanceof org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl)) - RuntimeDelegate.setInstance(new org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl()); + if (!(RuntimeDelegate.getInstance() instanceof AbstractRuntimeDelegate)) + RuntimeDelegate.setInstance(new RuntimeDelegateImpl()); } - public ODataCxfServer(String appBaseUri, Class odataApp, Class rootApp) { + public ODataCxfServer(String appBaseUri, Class odataApp, + Class rootApp) { this(appBaseUri); this.odataApp = odataApp; this.rootApp = rootApp; @@ -81,7 +84,7 @@ public ODataServer start() { CXFNonSpringJaxrsServlet odataServlet = new CXFNonSpringJaxrsServlet(); ServletHolder odataServletHolder = new ServletHolder(odataServlet); - odataServletHolder.setInitParameter("javax.ws.rs.Application", odataApp.getCanonicalName()); + odataServletHolder.setInitParameter("jakarta.ws.rs.Application", odataApp.getCanonicalName()); ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.addServlet(odataServletHolder, normalizePath(url.getPath()) + "/*"); @@ -89,7 +92,7 @@ public ODataServer start() { if (rootApp != null) { CXFNonSpringJaxrsServlet rootServlet = new CXFNonSpringJaxrsServlet(); ServletHolder rootServletHolder = new ServletHolder(rootServlet); - rootServletHolder.setInitParameter("javax.ws.rs.Application", rootApp.getCanonicalName()); + rootServletHolder.setInitParameter("jakarta.ws.rs.Application", rootApp.getCanonicalName()); contextHandler.addServlet(rootServletHolder, "/*"); } diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java index 661fed1..e6a7edf 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java @@ -1,25 +1,35 @@ package org.odata4j.examples.jersey.consumer; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.config.ClientConfig; +import org.glassfish.jersey.client.JerseyClient; +import org.glassfish.jersey.client.JerseyClientBuilder; + +import jakarta.ws.rs.client.Client; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.JerseyClient; +import org.glassfish.jersey.client.JerseyClientBuilder; /** * The default factory implementation for Jersey clients. * - *

      Use {@link #INSTANCE} to obtain a reference to the singleton instance of this factory.

      + *

      + * Use {@link #INSTANCE} to obtain a reference to the singleton instance of this + * factory. + *

      */ public class DefaultJerseyClientFactory implements JerseyClientFactory { public static final DefaultJerseyClientFactory INSTANCE = new DefaultJerseyClientFactory(); - private DefaultJerseyClientFactory() {} + private DefaultJerseyClientFactory() { + } /** - * Creates a new default {@link Client} by calling: Client.create(clientConfig) + * Creates a new default {@link Client} by calling: + * Client.create(clientConfig) */ @Override public Client createClient(ClientConfig clientConfig) { - Client client = Client.create(clientConfig); + JerseyClient client = JerseyClientBuilder.createClient(clientConfig); return client; } diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientFactory.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientFactory.java index 61d221d..50f78e6 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientFactory.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientFactory.java @@ -1,17 +1,18 @@ package org.odata4j.examples.jersey.consumer; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.config.ClientConfig; +import jakarta.ws.rs.client.Client; +import org.glassfish.jersey.client.ClientConfig; /** - * Client-side extension mechanism - provides a Jersey {@link Client} implementation given a configuration. + * Client-side extension mechanism - provides a Jersey {@link Client} + * implementation given a configuration. */ public interface JerseyClientFactory { /** * Creates a new Jersey client. * - * @param clientConfig the Jersey client api configuration + * @param clientConfig the Jersey client api configuration */ Client createClient(ClientConfig clientConfig); diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientResponse.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientResponse.java index 53514c8..8ccd841 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientResponse.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientResponse.java @@ -1,10 +1,10 @@ package org.odata4j.examples.jersey.consumer; -import javax.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.MultivaluedMap; import org.odata4j.consumer.ODataClientResponse; -import com.sun.jersey.api.client.ClientResponse; +import org.glassfish.jersey.client.ClientResponse; public class JerseyClientResponse implements ODataClientResponse { @@ -24,5 +24,7 @@ public MultivaluedMap getHeaders() { } @Override - public void close() {} + public void close() { + } + } diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientUtil.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientUtil.java index 968752c..13b5753 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientUtil.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/JerseyClientUtil.java @@ -1,60 +1,29 @@ package org.odata4j.examples.jersey.consumer; -import java.lang.reflect.Field; -import java.util.Set; - -import javax.ws.rs.ext.RuntimeDelegate; - +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.WebTarget; +import org.glassfish.jersey.client.ClientConfig; import org.odata4j.consumer.behaviors.OClientBehavior; -import org.odata4j.core.Throwables; import org.odata4j.examples.jersey.consumer.behaviors.JerseyClientBehavior; -import org.odata4j.examples.jersey.internal.StringProvider2; -import org.odata4j.internal.PlatformUtil; +import org.odata4j.urlencoder.ConversionUtil; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.core.impl.provider.header.MediaTypeProvider; -import com.sun.jersey.core.spi.factory.AbstractRuntimeDelegate; -import com.sun.jersey.spi.HeaderDelegateProvider; +import java.util.regex.Matcher; +import java.util.regex.Pattern; class JerseyClientUtil { - static { - if (PlatformUtil.runningOnAndroid()) - androidJerseyClientHack(); - } - - @SuppressWarnings("unchecked") - private static void androidJerseyClientHack() { - try { - RuntimeDelegate rd = RuntimeDelegate.getInstance(); - Field f = AbstractRuntimeDelegate.class.getDeclaredField("hps"); - f.setAccessible(true); - Set> hps = (Set>) f.get(rd); - hps.clear(); - hps.add(new MediaTypeProvider()); - } catch (Exception e) { - throw Throwables.propagate(e); - } - } - public static Client newClient(JerseyClientFactory clientFactory, OClientBehavior[] behaviors) { - DefaultClientConfig cc = new DefaultClientConfig(); - cc.getSingletons().add(new StringProvider2()); + ClientConfig cc = new ClientConfig(); if (behaviors != null) { - for (OClientBehavior behavior : behaviors) - { + for (OClientBehavior behavior : behaviors) { if (behavior instanceof JerseyClientBehavior) { ((JerseyClientBehavior) behavior).modify(cc); } } } Client client = clientFactory.createClient(cc); - if (behaviors != null) - { - for (OClientBehavior behavior : behaviors) - { + if (behaviors != null) { + for (OClientBehavior behavior : behaviors) { if (behavior instanceof JerseyClientBehavior) { ((JerseyClientBehavior) behavior).modifyClientFilters(client); } @@ -63,12 +32,10 @@ public static Client newClient(JerseyClientFactory clientFactory, OClientBehavio return client; } - public static WebResource resource(Client client, String url, OClientBehavior[] behaviors) { - WebResource resource = client.resource(url); - if (behaviors != null) - { - for (OClientBehavior behavior : behaviors) - { + public static WebTarget resource(Client client, String url, OClientBehavior[] behaviors) { + WebTarget resource = client.target(encodeURl(url)); + if (behaviors != null) { + for (OClientBehavior behavior : behaviors) { if (behavior instanceof JerseyClientBehavior) { ((JerseyClientBehavior) behavior).modifyWebResourceFilters(resource); } @@ -77,4 +44,41 @@ public static WebResource resource(Client client, String url, OClientBehavior[] return resource; } -} + /** + * + * ================================================================================================================= + * Fix bug Bug 171678 - query with primary keys hangs + * example primary keys: + * (pick_interpreter='SIM2',pick_name='100 (Top Stage + * IVF)',pick_obs_no=1,unique_wellbore_identifier='040292797601') + * The issues in the original code are: + * (1) matcher.find() takes very long time because Regular expression is invalid + * (2) If it does find the matches in some caes, it only returns part of primary + * key value "(xxx)" + * and will miss URL encoding special characters such as spaces before and after + * "(Top Stage IVF)" + * + * The fix is use RegEx "\\(([^(]+|(?))?\\)" and "\\(([^)]+|(?))?\\)" + * ============================================================================================= + * Original code: + * Regular expression '\\(([^)(]+|(?))+\\)' matches the string within the + * bracket in the URL. + * ================================================================================================ + * String in the bracket are OEntityKey which contain special character, + * here we are encoding the key in URL. + * + * @param url the url + * @return the string + */ + public static String encodeURl(String url) { + + Pattern pattern1 = Pattern.compile("\\((.*)\\)"); + Matcher matcher1 = pattern1.matcher(url); + while (matcher1.find()) { + String st = url.substring(matcher1.start(), matcher1.end()); + url = url.replace(st, ConversionUtil.encodeString(st)); + } + + return url; + } +} \ No newline at end of file diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java index 5cc1b2d..bea1b8e 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java @@ -1,73 +1,94 @@ package org.odata4j.examples.jersey.consumer; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.Field; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response.StatusType; - +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; +import org.glassfish.jersey.client.ClientResponse; +import org.glassfish.jersey.media.multipart.BodyPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.client.WebTarget; import org.core4j.Enumerable; import org.core4j.xml.XDocument; import org.core4j.xml.XmlFormat; -import org.odata4j.consumer.AbstractODataClient; -import org.odata4j.consumer.ODataClientRequest; -import org.odata4j.consumer.ODataClientResponse; -import org.odata4j.consumer.ODataConsumer; +import org.glassfish.jersey.message.internal.HttpHeaderReader; +import org.odata4j.consumer.*; import org.odata4j.consumer.behaviors.OClientBehavior; import org.odata4j.consumer.behaviors.OClientBehaviors; -import org.odata4j.core.ODataConstants; +import org.odata4j.core.*; import org.odata4j.core.ODataConstants.Charsets; -import org.odata4j.core.OError; -import org.odata4j.core.Throwables; +import org.odata4j.exceptions.BadRequestException; import org.odata4j.exceptions.ODataProducerException; import org.odata4j.exceptions.ODataProducerExceptions; -import org.odata4j.format.Entry; -import org.odata4j.format.FormatParserFactory; -import org.odata4j.format.FormatType; -import org.odata4j.format.FormatWriter; -import org.odata4j.format.FormatWriterFactory; -import org.odata4j.format.SingleLink; +import org.odata4j.exceptions.ServerErrorException; +import org.odata4j.format.*; import org.odata4j.internal.BOMWorkaroundReader; +import org.odata4j.internal.InternalUtil; import org.odata4j.stax2.XMLEventReader2; import org.odata4j.stax2.util.StaxUtil; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.ClientResponse.Status; -import com.sun.jersey.api.client.PartialRequestBuilder; -import com.sun.jersey.api.client.WebResource; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response.StatusType; +import java.io.*; +import java.lang.reflect.Field; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; /** * OData client based on Jersey. */ class ODataJerseyClient extends AbstractODataClient { - private final OClientBehavior[] requiredBehaviors = new OClientBehavior[] { OClientBehaviors.methodTunneling("MERGE") }; // jersey hates MERGE, tunnel through POST + public static final String MULTIPART_BASE = "multipart"; + public static final MediaType MULTIPART_BASE_TYPE = new MediaType(MULTIPART_BASE, null); + + private final OClientBehavior[] requiredBehaviors = new OClientBehavior[] { + OClientBehaviors.methodTunneling("MERGE") }; // jersey hates MERGE, tunnel through POST private final OClientBehavior[] behaviors; private final Client client; public ODataJerseyClient(FormatType type, JerseyClientFactory clientFactory, OClientBehavior... behaviors) { super(type); - this.behaviors = Enumerable.create(requiredBehaviors).concat(Enumerable.create(behaviors)).toArray(OClientBehavior.class); + this.behaviors = Enumerable.create(requiredBehaviors).concat(Enumerable.create(behaviors)) + .toArray(OClientBehavior.class); this.client = JerseyClientUtil.newClient(clientFactory, behaviors); } + /** + * Sets the ChunkedEncodingSize for jersey client. + */ + private int setClientChunKSize() { + // default to 32 MB + int clientChunKSize = 32 * 1024 * 1024; + ; + String chunkedEncodingSizeVarValue = InternalUtil + .getSystemPropertyValue(ODataConstants.JERSEY_CLIENT_CHUNKED_ENCODING_SIZE); + if (chunkedEncodingSizeVarValue != null && !chunkedEncodingSizeVarValue.isEmpty()) { + try { + // The value passed on the system variable is in MB and we need to convert it to + // bytes + clientChunKSize = Integer.parseInt(chunkedEncodingSizeVarValue) * 1024 * 1024; + ; + } catch (NumberFormatException numFormatException) { + // We ignore the exception and use default; + } + } + return clientChunKSize; + } + public Reader getFeedReader(ODataClientResponse response) { ClientResponse clientResponse = ((JerseyClientResponse) response).getClientResponse(); if (ODataConsumer.dump.responseBody()) { - String textEntity = clientResponse.getEntity(String.class); - dumpResponseBody(textEntity, clientResponse.getType()); + String textEntity = clientResponse.readEntity(String.class); + dumpResponseBody(textEntity, clientResponse.getMediaType()); return new BOMWorkaroundReader(new StringReader(textEntity)); } - InputStream textEntity = clientResponse.getEntityInputStream(); + InputStream textEntity = clientResponse.getEntityStream(); try { return new BOMWorkaroundReader(new InputStreamReader(textEntity, Charsets.Upper.UTF_8)); } catch (Exception e) { @@ -76,27 +97,167 @@ public Reader getFeedReader(ODataClientResponse response) { } public String requestBody(FormatType formatType, ODataClientRequest request) throws ODataProducerException { - ODataClientResponse response = doRequest(formatType, request, Status.OK); - String entity = ((JerseyClientResponse) response).getClientResponse().getEntity(String.class); + ODataClientResponse response = doRequest(formatType, request, Response.Status.OK); + String entity = ((JerseyClientResponse) response).getClientResponse().readEntity(String.class); response.close(); return entity; } + // /** + // * This is consumer side to create a batch request, and then handle the + // * response. + // * + // * @param batchRequest + // * the batchRequest is a POST with end point $batch, the + // * content-type should be multipart/mixed. + // * @param childRequests + // * this is a list of the operation that will be part of the + // * batch request. it can also contain + // * change set. + // * + // */ + // public List batchRequest(FormatType reqType1, + // ODataClientRequest batchRequest, + // List childRequests) { + + // List result = null; + // if (behaviors != null) { + // for (OClientBehavior behavior : behaviors) + // batchRequest = behavior.transform(batchRequest); + // } + + // WebTarget webResource = JerseyClientUtil.resource(client, + // batchRequest.getUrl(), behaviors); + // Invocation.Builder b = webResource.request(); + // String boundary = null; + // String cType = null; + + // FormatType formatType = getFormatType(); + // // set headers + // b = b.accept(formatType.getAcceptableMediaTypes()); + + // for (String header : batchRequest.getHeaders().keySet()) { + // // parse content type to get the boundary string + // if (header.equals(ODataConstants.Headers.CONTENT_TYPE)) { + // cType = batchRequest.getHeaders().get(header); + // boundary = cType.substring(cType.indexOf('=') + 1); + // } + // b.header(header, batchRequest.getHeaders().get(header)); + // } + + // if (ODataConsumer.dump.requestHeaders()) + // dumpHeaders(batchRequest, webResource, b); + + // if (boundary == null) { + // throw new BadRequestException("batchRequest's content type should contain + // boundary"); + // } + // // now create the pay load for the batch request + // StringBuilder sb = new StringBuilder(); + // for (Object req : childRequests) { + // // new way to add the request + // sb.append("\n--").append(boundary).append("\n"); + // sb.append(((OBatchSupport) req).formatRequest(this.getFormatType())); + // } + + // // ending the batch multi part + // if (childRequests.size() > 0) { + // sb.append("\n--").append(boundary).append("--\n"); + // } + + // String entity = sb.toString(); + + // if (ODataConsumer.dump.requestBody()) { + // dump(entity); + // } + + // // execute request + // ClientResponse response = b.method(batchRequest.getMethod(), + // Entity.entity(entity, cType), ClientResponse.class); + // Integer status = response.getStatus(); + // String responseContentType = + // response.getHeaders().getFirst(ODataConstants.Headers.CONTENT_TYPE); + // MediaType mType = getMediaType(responseContentType); + // // check the response if it is multi part, if not, an error occured, throw + // // exception + // if (!mType.isCompatible(MULTIPART_BASE_TYPE)) { + // String errMsg = response.readEntity(String.class); + // OError error = OErrors.error(status.toString(), errMsg, null); + // throw new ServerErrorException.Factory().createException(error); + // } + // result = parseResponse(response, childRequests); + + // return result; + // } + + // private List parseResponse(ClientResponse response, + // List childRequests) { + + // ODataVersion version = + // InternalUtil.getDataServiceVersion(response.getHeaders() + // .getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); + + // MultiPart mp = response.readEntity(MultiPart.class); // input stream can only + // be consumed once + + // // this is the list will hold individual request result. + // List batchResultList = new + // ArrayList(childRequests.size()); + + // if (ODataConsumer.dump.responseHeaders()) { + // dumpHeaders(response); + // } + + // int i = 0; + // for (BodyPart bp : mp.getBodyParts()) { + // ODataClientBatchResponse ocbr = null; + // MediaType cType = bp.getMediaType(); + // if (cType.isCompatible(new MediaType("multipart", "mixed"))) { + // MultiPart cmp = bp.getEntityAs(MultiPart.class); + // OChangeSetRequest csr = (OChangeSetRequest) childRequests.get(i); + + // List payloadList = new ArrayList(); + + // for (BodyPart cbp : cmp.getBodyParts()) { + // String content = cbp.getEntityAs(String.class); + // payloadList.add(content); + // } + // ocbr = ConsumerBatchRequestHelper.parseChangeSetOperationResponse(version, + // payloadList, csr, getFormatType()); + // } else { + // String content = bp.getEntityAs(String.class); + // OBatchSupport so = (OBatchSupport) childRequests.get(i); + // ocbr = ConsumerBatchRequestHelper.parseSingleOperationResponse(version, + // content, so, getFormatType()); + // } + + // batchResultList.add(ocbr); + // i++; + // } + + // return batchResultList; + // } + @SuppressWarnings("unchecked") - protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, StatusType... expectedResponseStatus) throws ODataProducerException { + protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, + StatusType... expectedResponseStatus) throws ODataProducerException { if (behaviors != null) { for (OClientBehavior behavior : behaviors) request = behavior.transform(request); } + // if(request.getPayload() != null && request.getPayload() instanceof + // InputStream) { + // this.client.setChunkedEncodingSize(setClientChunKSize()); + // } - WebResource webResource = JerseyClientUtil.resource(client, request.getUrl(), behaviors); + WebTarget webResource = JerseyClientUtil.resource(client, request.getUrl(), behaviors); // set query params for (String qpn : request.getQueryParams().keySet()) webResource = webResource.queryParam(qpn, request.getQueryParams().get(qpn)); - WebResource.Builder b = webResource.getRequestBuilder(); + Invocation.Builder b = webResource.request(); // set headers b = b.accept(reqType.getAcceptableMediaTypes()); @@ -110,6 +271,7 @@ protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest r dumpHeaders(request, webResource, b); // request body + Entity payloadEntity = null; if (request.getPayload() != null) { Class payloadClass; @@ -117,47 +279,55 @@ protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest r payloadClass = Entry.class; else if (request.getPayload() instanceof SingleLink) payloadClass = SingleLink.class; + // else if (request.getPayload() instanceof Parameters) + // payloadClass = Parameters.class; + else if (request.getPayload() instanceof InputStream) + payloadClass = InputStream.class; else throw new IllegalArgumentException("Unsupported payload: " + request.getPayload()); - StringWriter sw = new StringWriter(); - FormatWriter fw = (FormatWriter) - FormatWriterFactory.getFormatWriter(payloadClass, null, this.getFormatType().toString(), null); - fw.write(null, sw, request.getPayload()); - - String entity = sw.toString(); - if (ODataConsumer.dump.requestBody()) - dump(entity); - - // allow the client to override the default format writer content-type - String contentType = request.getHeaders().containsKey(ODataConstants.Headers.CONTENT_TYPE) - ? request.getHeaders().get(ODataConstants.Headers.CONTENT_TYPE) - : fw.getContentType(); - - b.entity(entity, contentType); + if (request.getPayload() instanceof InputStream) { + // send media stream as payload + String contentType = request.getHeaders().containsKey(ODataConstants.Headers.CONTENT_TYPE) + ? request.getHeaders().get(ODataConstants.Headers.CONTENT_TYPE) + : ODataConstants.APPLICATION_OCTET_STREAM; + payloadEntity = Entity.entity(request.getPayload(), contentType); + } else { + StringWriter sw = new StringWriter(); + FormatWriter fw = (FormatWriter) FormatWriterFactory.getFormatWriter(payloadClass, null, + this.getFormatType().toString(), null); + fw.write(null, sw, request.getPayload()); + + String entity = sw.toString(); + if (ODataConsumer.dump.requestBody()) + dump(entity); + + // allow the client to override the default format writer content-type + String contentType = request.getHeaders().containsKey(ODataConstants.Headers.CONTENT_TYPE) + ? request.getHeaders().get(ODataConstants.Headers.CONTENT_TYPE) + : fw.getContentType(); + + payloadEntity = Entity.entity(entity, contentType); + } } // execute request - ClientResponse response = null; - try { - response = b.method(request.getMethod(), ClientResponse.class); - } catch (ClientHandlerException e) { - Throwables.propagate(e); - } + ClientResponse response = b.method(request.getMethod(), payloadEntity, ClientResponse.class); if (ODataConsumer.dump.responseHeaders()) dumpHeaders(response); - StatusType status = response.getClientResponseStatus(); + StatusType status = response.getStatusInfo(); for (StatusType expStatus : expectedResponseStatus) if (expStatus.getStatusCode() == status.getStatusCode()) return new JerseyClientResponse(response); // the server responded with an unexpected status RuntimeException exception; - String textEntity = response.getEntity(String.class); // input stream can only be consumed once + String textEntity = response.readEntity(String.class); // input stream can only be consumed once try { - // report error as ODataProducerException in case we get a well-formed OData error... - MediaType contentType = response.getType(); + // report error as ODataProducerException in case we get a well-formed OData + // error... + MediaType contentType = response.getMediaType(); OError error = FormatParserFactory.getParser(OError.class, contentType, null).parse(new StringReader(textEntity)); exception = ODataProducerExceptions.create(status, error); } catch (RuntimeException e) { @@ -172,14 +342,15 @@ protected XMLEventReader2 toXml(ODataClientResponse response) { ClientResponse clientResponse = ((JerseyClientResponse) response).getClientResponse(); if (ODataConsumer.dump.responseBody()) { - String textEntity = clientResponse.getEntity(String.class); - dumpResponseBody(textEntity, clientResponse.getType()); + String textEntity = clientResponse.readEntity(String.class); + dumpResponseBody(textEntity, clientResponse.getMediaType()); return StaxUtil.newXMLEventReader(new BOMWorkaroundReader(new StringReader(textEntity))); } - InputStream textEntity = clientResponse.getEntityInputStream(); + InputStream textEntity = clientResponse.getEntityStream(); try { - return StaxUtil.newXMLEventReader(new BOMWorkaroundReader(new InputStreamReader(textEntity, Charsets.Upper.UTF_8))); + return StaxUtil + .newXMLEventReader(new BOMWorkaroundReader(new InputStreamReader(textEntity, Charsets.Upper.UTF_8))); } catch (Exception e) { throw Throwables.propagate(e); } @@ -190,7 +361,8 @@ private void dumpResponseBody(String textEntity, MediaType type) { if (type.toString().contains("xml") || logXml != null && logXml.startsWith(" getRequestHeaders(WebResource.Builder b) { - if (dontTryRequestHeaders) - return null; - - // protected MultivaluedMap metadata; - try { - Field f = PartialRequestBuilder.class.getDeclaredField("metadata"); - f.setAccessible(true); - return (MultivaluedMap) f.get(b); - } catch (Exception e) { - dontTryRequestHeaders = true; - return null; - } - + private MultivaluedMap getRequestHeaders(Invocation.Builder b) { + // if (dontTryRequestHeaders) + // return null; + // + // protected MultivaluedMap metadata; + // try { + // Field f = PartialRequestBuilder.class.getDeclaredField("metadata"); + // f.setAccessible(true); + // return (MultivaluedMap) f.get(b); + // } catch (Exception e) { + dontTryRequestHeaders = true; + return null; + // } + // } - private void dumpHeaders(ODataClientRequest request, WebResource webResource, WebResource.Builder b) { + private void dumpHeaders(ODataClientRequest request, WebTarget webResource, Invocation.Builder b) { dump(request.getMethod() + " " + webResource); dump(getRequestHeaders(b)); } @@ -237,4 +409,26 @@ private static void dump(String message) { System.out.println(message); } -} + /** + * create the MediaType instance based on content type + * + * @param contentType + * @return + */ + public static MediaType getMediaType(String contentType) { + try { + List list = new ArrayList(); + list = HttpHeaderReader.readMediaTypes(list, contentType); + return list.get(0); + } catch (ParseException e) { + throw new IllegalArgumentException("cannot parse the content type " + contentType); + } + } + + public Reader getFeedReader(String textEntity) { + if (ODataConsumer.dump.responseBody()) { + dump(textEntity); + } + return new BOMWorkaroundReader(new StringReader(textEntity)); + } +} \ No newline at end of file diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyConsumer.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyConsumer.java index 8ac4275..e96ddf3 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyConsumer.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyConsumer.java @@ -1,7 +1,9 @@ package org.odata4j.examples.jersey.consumer; -import javax.ws.rs.ext.RuntimeDelegate; +import jakarta.ws.rs.ext.RuntimeDelegate; +import org.glassfish.jersey.internal.AbstractRuntimeDelegate; +import org.glassfish.jersey.internal.RuntimeDelegateImpl; import org.odata4j.consumer.AbstractODataConsumer; import org.odata4j.consumer.ODataClient; import org.odata4j.consumer.ODataConsumer; @@ -15,12 +17,14 @@ public class ODataJerseyConsumer extends AbstractODataConsumer { private ODataJerseyClient client; - private ODataJerseyConsumer(FormatType type, String serviceRootUri, JerseyClientFactory clientFactory, OClientBehavior... behaviors) { + private ODataJerseyConsumer(FormatType type, String serviceRootUri, JerseyClientFactory clientFactory, + OClientBehavior... behaviors) { super(serviceRootUri); - // ensure that a correct JAX-RS implementation (Jersey, server or default) is loaded - if (!(RuntimeDelegate.getInstance() instanceof com.sun.jersey.core.spi.factory.AbstractRuntimeDelegate)) - RuntimeDelegate.setInstance(new com.sun.ws.rs.ext.RuntimeDelegateImpl()); + // ensure that a correct JAX-RS implementation (Jersey, server or default) is + // loaded + if (!(RuntimeDelegate.getInstance() instanceof AbstractRuntimeDelegate)) + RuntimeDelegate.setInstance(new RuntimeDelegateImpl()); this.client = new ODataJerseyClient(type, clientFactory, behaviors); } @@ -49,7 +53,7 @@ private Builder(String serviceRootUri) { /** * Sets a preferred {@link FormatType}. Defaults to {@code FormatType.ATOM}. * - * @param formatType the format type + * @param formatType the format type * @return this builder */ public Builder setFormatType(FormatType formatType) { @@ -60,7 +64,7 @@ public Builder setFormatType(FormatType formatType) { /** * Sets a specific {@link JerseyClientFactory}. * - * @param clientFactory the jersey client factory + * @param clientFactory the jersey client factory * @return this builder */ public Builder setClientFactory(JerseyClientFactory clientFactory) { @@ -71,9 +75,11 @@ public Builder setClientFactory(JerseyClientFactory clientFactory) { /** * Sets one or more client behaviors. * - *

      Client behaviors transform http requests to interact with services that require custom extensions. + *

      + * Client behaviors transform http requests to interact with services that + * require custom extensions. * - * @param clientBehaviors the client behaviors + * @param clientBehaviors the client behaviors * @return this builder */ public Builder setClientBehaviors(OClientBehavior... clientBehaviors) { @@ -97,7 +103,7 @@ public ODataJerseyConsumer build() { /** * Constructs a new builder for an {@link ODataJerseyConsumer} object. * - * @param serviceRootUri the OData service root uri + * @param serviceRootUri the OData service root uri */ public static Builder newBuilder(String serviceRootUri) { return new Builder(serviceRootUri); @@ -106,9 +112,14 @@ public static Builder newBuilder(String serviceRootUri) { /** * Creates a new consumer for the given OData service uri. * - *

      Wrapper for {@code ODataJerseyConsumer.newBuilder(serviceRootUri).build()}. + *

      + * Wrapper for {@code ODataJerseyConsumer.newBuilder(serviceRootUri).build()}. * - * @param serviceRootUri the service uri

      e.g. http://services.odata.org/Northwind/Northwind.svc/

      + * @param serviceRootUri the service uri + *

      + * e.g. + * http://services.odata.org/Northwind/Northwind.svc/ + *

      * @return a new OData consumer */ public static ODataJerseyConsumer create(String serviceRootUri) { diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/AllowSelfSignedCertsBehavior.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/AllowSelfSignedCertsBehavior.java deleted file mode 100644 index 6c52660..0000000 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/AllowSelfSignedCertsBehavior.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.odata4j.examples.jersey.consumer.behaviors; - -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import org.odata4j.consumer.ODataClientRequest; -import org.odata4j.consumer.behaviors.OClientBehavior; -import org.odata4j.core.Throwables; - -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.filter.Filterable; -import com.sun.jersey.client.urlconnection.HTTPSProperties; - -public enum AllowSelfSignedCertsBehavior implements JerseyClientBehavior { - - INSTANCE; - - @Override - public ODataClientRequest transform(ODataClientRequest request) { - return request; - } - - @Override - public void modify(ClientConfig clientConfig) { - - HostnameVerifier hv = new HostnameVerifier() { - public boolean verify(String urlHostName, SSLSession session) { - // Write a warning, as there is certainly a potential security implication here. - System.out.println(String.format("Warning: URL Host: '%s' does not equal '%s'", urlHostName, session.getPeerHost())); - return true; - } - }; - - TrustManager[] trustAll = new TrustManager[] { - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[] {}; - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} - } - }; - - try { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, trustAll, new SecureRandom()); - HTTPSProperties props = new HTTPSProperties(hv, context); - clientConfig.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, props); - } catch (Exception e) { - throw Throwables.propagate(e); - } - } - - @Override - public void modifyClientFilters(Filterable client) {} - - @Override - public void modifyWebResourceFilters(Filterable webResource) {} - - /** - * Creates a behavior that allows for https services with self-signed certificates. - * - * @return a behavior that allows for https services with self-signed certificates - */ - public static OClientBehavior allowSelfSignedCerts() { - return AllowSelfSignedCertsBehavior.INSTANCE; - } - -} diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/JerseyClientBehavior.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/JerseyClientBehavior.java index ea268a6..78d2d58 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/JerseyClientBehavior.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/behaviors/JerseyClientBehavior.java @@ -1,16 +1,17 @@ package org.odata4j.examples.jersey.consumer.behaviors; +import jakarta.ws.rs.client.ClientRequestFilter; +import jakarta.ws.rs.core.Configurable; import org.odata4j.consumer.behaviors.OClientBehavior; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.filter.Filterable; +import org.glassfish.jersey.client.ClientConfig; public interface JerseyClientBehavior extends OClientBehavior { public void modify(ClientConfig clientConfig); - public void modifyClientFilters(Filterable client); + public void modifyClientFilters(Configurable client); - public void modifyWebResourceFilters(Filterable webResource); + public void modifyWebResourceFilters(Configurable webResource); -} +} \ No newline at end of file diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/internal/StringProvider2.java b/test-integration/src/main/java/org/odata4j/examples/jersey/internal/StringProvider2.java index 42082ea..00c1bd5 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/internal/StringProvider2.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/internal/StringProvider2.java @@ -1,5 +1,8 @@ package org.odata4j.examples.jersey.internal; +import org.glassfish.jersey.message.internal.AbstractMessageReaderWriterProvider; +import org.glassfish.jersey.message.internal.ReaderWriter; + import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; @@ -9,13 +12,10 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Type; -import javax.ws.rs.Consumes; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider; -import com.sun.jersey.core.util.ReaderWriter; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; @Produces({ "text/plain", "*/*" }) @Consumes({ "text/plain", "*/*" }) @@ -25,7 +25,8 @@ public boolean isReadable(Class type, Type genericType, Annotation annotation return type == String.class; } - public String readFrom(Class type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { + public String readFrom(Class type, Type genericType, Annotation annotations[], MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { return readFromAsString(entityStream, mediaType); } @@ -33,10 +34,15 @@ public boolean isWriteable(Class type, Type genericType, Annotation annotatio return type == String.class; } - public void writeTo(String t, Class type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { + public void writeTo(String t, Class type, Type genericType, Annotation annotations[], MediaType mediaType, + MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { // writeToAsString(t, entityStream, mediaType); - Writer osw = new BufferedWriter(new OutputStreamWriter(entityStream, ReaderWriter.getCharset(mediaType)), 8 * 1024); // explicit 8k size FOR ANDROID + Writer osw = new BufferedWriter(new OutputStreamWriter(entityStream, ReaderWriter.getCharset(mediaType)), 8 * 1024); // explicit + // 8k + // size + // FOR + // ANDROID osw.write(t); osw.flush(); } diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/producer/resources/ODataProducerProvider.java b/test-integration/src/main/java/org/odata4j/examples/jersey/producer/resources/ODataProducerProvider.java index de551e7..37e7a58 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/producer/resources/ODataProducerProvider.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/producer/resources/ODataProducerProvider.java @@ -2,19 +2,23 @@ import java.util.Properties; -import javax.ws.rs.core.Context; -import javax.ws.rs.ext.Provider; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.ext.Provider; import org.odata4j.producer.ODataProducer; import org.odata4j.producer.resources.DefaultODataProducerProvider; -import com.sun.jersey.api.core.ResourceConfig; +import org.glassfish.jersey.server.ResourceConfig; /** * Jersey-specific OData producer provider. * - *

      This provider allows specifying a factory as part of the container's deployment - * descriptor (web.xml). The factory is used to create an OData producer instance. + *

      + * This provider allows specifying a factory as part of the container's + * deployment + * descriptor (web.xml). The factory is used to create an OData producer + * instance. + * *

        * {@code
        * 
      diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/producer/server/ODataJerseyServer.java b/test-integration/src/main/java/org/odata4j/examples/jersey/producer/server/ODataJerseyServer.java
      index 5beedc7..d5ee873 100644
      --- a/test-integration/src/main/java/org/odata4j/examples/jersey/producer/server/ODataJerseyServer.java
      +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/producer/server/ODataJerseyServer.java
      @@ -1,10 +1,5 @@
       package org.odata4j.examples.jersey.producer.server;
       
      -import static com.sun.jersey.api.core.ResourceConfig.FEATURE_TRACE;
      -import static com.sun.jersey.api.core.ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS;
      -import static com.sun.jersey.api.core.ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS;
      -import static com.sun.jersey.api.core.ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES;
      -
       import java.io.IOException;
       import java.util.ArrayList;
       import java.util.HashMap;
      @@ -15,20 +10,21 @@
       import java.util.concurrent.TimeUnit;
       import java.util.logging.Logger;
       
      -import javax.ws.rs.core.Application;
      -import javax.ws.rs.ext.RuntimeDelegate;
      +import jakarta.ws.rs.container.ContainerRequestFilter;
      +import jakarta.ws.rs.container.ContainerResponseFilter;
      +import jakarta.ws.rs.core.Application;
      +import jakarta.ws.rs.ext.RuntimeDelegate;
       
       import org.core4j.CoreUtils;
       import org.core4j.Enumerable;
      +import org.glassfish.jersey.internal.AbstractRuntimeDelegate;
      +import org.glassfish.jersey.internal.RuntimeDelegateImpl;
      +import org.glassfish.jersey.server.ContainerFactory;
      +import org.glassfish.jersey.server.ResourceConfig;
      +import org.glassfish.jersey.test.TestProperties;
       import org.odata4j.core.Throwables;
       import org.odata4j.producer.server.ODataServer;
       
      -import com.sun.jersey.api.container.ContainerFactory;
      -import com.sun.jersey.api.container.httpserver.HttpServerFactory;
      -import com.sun.jersey.api.core.ApplicationAdapter;
      -import com.sun.jersey.spi.container.ContainerRequestFilter;
      -import com.sun.jersey.spi.container.ContainerResponseFilter;
      -import com.sun.jersey.spi.container.ResourceFilterFactory;
       import com.sun.net.httpserver.Authenticator;
       import com.sun.net.httpserver.Filter;
       import com.sun.net.httpserver.HttpContext;
      @@ -58,11 +54,12 @@ public ODataJerseyServer(String appBaseUri) {
           this.appBaseUri = appBaseUri;
       
           // ensure that the correct JAX-RS implementation (Jersey, server) is loaded
      -    if (!(RuntimeDelegate.getInstance() instanceof com.sun.jersey.server.impl.provider.RuntimeDelegateImpl))
      -      RuntimeDelegate.setInstance(new com.sun.jersey.server.impl.provider.RuntimeDelegateImpl());
      +    if (!(RuntimeDelegate.getInstance() instanceof AbstractRuntimeDelegate))
      +      RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
         }
       
      -  public ODataJerseyServer(String appBaseUri, Class odataApp, Class rootApp) {
      +  public ODataJerseyServer(String appBaseUri, Class odataApp,
      +      Class rootApp) {
           this(appBaseUri);
           this.odataApp = odataApp;
           this.rootApp = rootApp;
      @@ -90,14 +87,12 @@ public  ODataJerseyServer addJerseyResponseFi
           return this;
         }
       
      -  public  ODataJerseyServer addJerseyResourceFilter(Class filter) {
      -    jerseyResourceFilters.add(filter.getName());
      -    return this;
      -  }
      -
      -  /** Enabling this feature can be useful in tracking down issues related to selecting the resource class */
      +  /**
      +   * Enabling this feature can be useful in tracking down issues related to
      +   * selecting the resource class
      +   */
         public ODataJerseyServer setJerseyTrace(boolean enabled) {
      -    return setJerseyFeature(FEATURE_TRACE, enabled);
      +    return setJerseyFeature(TestProperties.LOG_TRAFFIC, enabled);
         }
       
         public ODataJerseyServer setJerseyFeature(String feature, boolean value) {
      @@ -123,7 +118,7 @@ public ODataServer stop() {
         /**
          * Stops synchronously, handy for unit test scenarios.
          *
      -   * @param delaySeconds  seconds to wait for clean termination
      +   * @param delaySeconds seconds to wait for clean termination
          * @return this instance for call chaining
          */
         public ODataJerseyServer stop(int delaySeconds) {
      @@ -148,38 +143,42 @@ public ODataServer start() {
           if (odataApp == null)
             throw new RuntimeException("ODataApplication not set");
       
      -    try {
      -      Map propertiesAndFeatures = buildPropertiesAndFeatures();
      -
      -      // create resource config/ application adapter for app context
      -      ApplicationAdapter odataAppAdapter = new ApplicationAdapter(odataApp.newInstance());
      -      odataAppAdapter.setPropertiesAndFeatures(propertiesAndFeatures);
      -      server = HttpServerFactory.create(appBaseUri, odataAppAdapter);
      -
      -      // create resource config/ application adapter for root context (if necessary)
      -      if (rootApp != null) {
      -        ApplicationAdapter rootAppAdapter = new ApplicationAdapter(rootApp.newInstance());
      -        rootAppAdapter.setPropertiesAndFeatures(propertiesAndFeatures);
      -        HttpHandler rootHttpHandler = ContainerFactory.createContainer(HttpHandler.class, rootAppAdapter);
      -        server.createContext("/", rootHttpHandler);
      -      }
      -
      -      // initialize all contexts
      -      for (HttpContext context : getHttpContexts())
      -        initHttpContext(context);
      -
      -      // fire up the HttpServer
      -      server.start();
      -
      -      LOG.info(String.format("Jersey app started with WADL available at %sapplication.wadl\n", appBaseUri));
      -      return this;
      -    } catch (IOException e) {
      -      throw Throwables.propagate(e);
      -    } catch (InstantiationException e) {
      -      throw Throwables.propagate(e);
      -    } catch (IllegalAccessException e) {
      -      throw Throwables.propagate(e);
      -    }
      +    // try {
      +    Map propertiesAndFeatures = buildPropertiesAndFeatures();
      +
      +    // // create resource config/ application adapter for app context
      +    // ApplicationAdapter odataAppAdapter = new
      +    // ApplicationAdapter(odataApp.newInstance());
      +    // odataAppAdapter.setPropertiesAndFeatures(propertiesAndFeatures);
      +    // server = HttpServerFactory.create(appBaseUri, odataAppAdapter);
      +    //
      +    // // create resource config/ application adapter for root context (if
      +    // necessary)
      +    // if (rootApp != null) {
      +    // ApplicationAdapter rootAppAdapter = new
      +    // ApplicationAdapter(rootApp.newInstance());
      +    // rootAppAdapter.setPropertiesAndFeatures(propertiesAndFeatures);
      +    // HttpHandler rootHttpHandler =
      +    // ContainerFactory.createContainer(HttpHandler.class, rootAppAdapter);
      +    // server.createContext("/", rootHttpHandler);
      +    // }
      +
      +    // initialize all contexts
      +    for (HttpContext context : getHttpContexts())
      +      initHttpContext(context);
      +
      +    // fire up the HttpServer
      +    server.start();
      +
      +    LOG.info(String.format("Jersey app started with WADL available at %sapplication.wadl\n", appBaseUri));
      +    return this;
      +    //// } catch (IOException e) {
      +    //// throw Throwables.propagate(e);
      +    // } catch (InstantiationException e) {
      +    // throw Throwables.propagate(e);
      +    // } catch (IllegalAccessException e) {
      +    // throw Throwables.propagate(e);
      +    // }
         }
       
         protected HttpServer getHttpServer() {
      @@ -188,9 +187,12 @@ protected HttpServer getHttpServer() {
       
         protected Map buildPropertiesAndFeatures() {
           Map propertiesAndFeatures = new HashMap();
      -    propertiesAndFeatures.put(PROPERTY_CONTAINER_REQUEST_FILTERS, Enumerable.create(jerseyRequestFilters).toArray(String.class));
      -    propertiesAndFeatures.put(PROPERTY_CONTAINER_RESPONSE_FILTERS, Enumerable.create(jerseyResponseFilters).toArray(String.class));
      -    propertiesAndFeatures.put(PROPERTY_RESOURCE_FILTER_FACTORIES, Enumerable.create(jerseyResourceFilters).toArray(String.class));
      +    // propertiesAndFeatures.put(PROPERTY_CONTAINER_REQUEST_FILTERS,
      +    // Enumerable.create(jerseyRequestFilters).toArray(String.class));
      +    // propertiesAndFeatures.put(PROPERTY_CONTAINER_RESPONSE_FILTERS,
      +    // Enumerable.create(jerseyResponseFilters).toArray(String.class));
      +    // propertiesAndFeatures.put(PROPERTY_RESOURCE_FILTER_FACTORIES,
      +    // Enumerable.create(jerseyResourceFilters).toArray(String.class));
           propertiesAndFeatures.putAll(jerseyFeatures);
           return propertiesAndFeatures;
         }
      @@ -209,4 +211,4 @@ protected Iterable getHttpContexts() {
           tmp = CoreUtils.getFieldValue(tmp, "list", Object.class);
           return (List) tmp;
         }
      -}
      +}
      \ No newline at end of file
      diff --git a/test-integration/src/test/java/org/odata4j/test/integration/AbstractIntegrationTest.java b/test-integration/src/test/java/org/odata4j/test/integration/AbstractIntegrationTest.java
      index 0180751..5503297 100644
      --- a/test-integration/src/test/java/org/odata4j/test/integration/AbstractIntegrationTest.java
      +++ b/test-integration/src/test/java/org/odata4j/test/integration/AbstractIntegrationTest.java
      @@ -1,18 +1,39 @@
       package org.odata4j.test.integration;
       
      +import java.io.IOException;
      +import java.net.ServerSocket;
      +import java.util.concurrent.atomic.AtomicInteger;
       import org.junit.After;
       import org.junit.Before;
       import org.odata4j.producer.server.ODataServer;
      +import org.odata4j.test.integration.AbstractRuntimeTest.RuntimeFacadeType;
       
       /**
        * Base integration test class that:
      - * 
      1. starts an ODataServer,
      2. + *
          + *
        1. starts an ODataServer,
        2. *
        3. registers an ODataProducer,
        4. - *
        5. and starts a client
        + *
      3. and starts a client
      4. + *
      */ public abstract class AbstractIntegrationTest extends AbstractRuntimeTest { - protected static final String BASE_URI = "http://localhost:8888/test.svc/"; + private static final AtomicInteger portCounter = new AtomicInteger(9000); + + private static int getNextAvailablePort() { + int basePort = portCounter.getAndIncrement(); + // Try the base port first, then increment until we find an available port + for (int port = basePort; port < basePort + 100; port++) { + try (ServerSocket socket = new ServerSocket(port)) { + return port; + } catch (IOException e) { + // Port is in use, try the next one + } + } + throw new RuntimeException("Could not find an available port starting from " + basePort); + } + + protected final String BASE_URI; /** * The ODataServer instance. @@ -21,6 +42,9 @@ public abstract class AbstractIntegrationTest extends AbstractRuntimeTest { public AbstractIntegrationTest(RuntimeFacadeType type) { super(type); + // Each test instance gets its own port to avoid conflicts + int port = getNextAvailablePort(); + this.BASE_URI = "http://localhost:" + port + "/test.svc/"; } @Before @@ -47,6 +71,8 @@ protected void startODataServer() throws Exception { protected abstract void stopClient() throws Exception; protected void stopODataServer() throws Exception { - server.stop(); + if (server != null) { + server.stop(); + } } } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/AbstractJettyHttpClientTest.java b/test-integration/src/test/java/org/odata4j/test/integration/AbstractJettyHttpClientTest.java index a7d08c2..cb4f04e 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/AbstractJettyHttpClientTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/AbstractJettyHttpClientTest.java @@ -1,7 +1,7 @@ package org.odata4j.test.integration; -import org.eclipse.jetty.client.ContentExchange; import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.api.ContentResponse; /** * Base integration test class that uses a Jetty HTTP client. @@ -20,7 +20,6 @@ public AbstractJettyHttpClientTest(RuntimeFacadeType type) { @Override protected void startClient() throws Exception { client = new HttpClient(); - client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); client.start(); } @@ -32,11 +31,8 @@ protected void stopClient() throws Exception { /** * Helper method to send an HTTP request. */ - protected ContentExchange sendRequest(String url) throws Exception { - ContentExchange exchange = new ContentExchange(true); - exchange.setURL(url); - client.send(exchange); - exchange.waitForDone(); - return exchange; + protected ContentResponse sendRequest(String url) throws Exception { + ContentResponse response = client.GET(url); + return response; } } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/AbstractRuntimeTest.java b/test-integration/src/test/java/org/odata4j/test/integration/AbstractRuntimeTest.java index 0cb3a1e..5834823 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/AbstractRuntimeTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/AbstractRuntimeTest.java @@ -42,7 +42,8 @@ protected void logRule() { PropertyConfigurator.configure(p); // configure JUL - java.util.logging.LogManager.getLogManager().readConfiguration(AbstractRuntimeTest.class.getResourceAsStream("/logging.properties")); + java.util.logging.LogManager.getLogManager() + .readConfiguration(AbstractRuntimeTest.class.getResourceAsStream("/logging.properties")); } catch (Exception e) { throw Throwables.propagate(e); } @@ -75,7 +76,7 @@ private void logTestClassContext(Class c, FrameworkMethod method) { private final static String RUNTIME_ENVIRONMENT_PROPERTY = "org.odata4j.jaxrs.runtime"; - protected enum RuntimeFacadeType { + public enum RuntimeFacadeType { JERSEY, CXF; public static RuntimeFacadeType fromString(String value) { @@ -87,7 +88,8 @@ public static RuntimeFacadeType fromString(String value) { } else if ("CXF".equals(value)) { st = CXF; } else { - throw new IllegalArgumentException("Wrong value for " + AbstractRuntimeTest.RUNTIME_ENVIRONMENT_PROPERTY + " = " + value + ". Allowed is [JERSEY|CXF]"); + throw new IllegalArgumentException("Wrong value for " + AbstractRuntimeTest.RUNTIME_ENVIRONMENT_PROPERTY + " = " + + value + ". Allowed is [JERSEY|CXF]"); } return st; @@ -98,14 +100,14 @@ public static RuntimeFacadeType fromString(String value) { public AbstractRuntimeTest(RuntimeFacadeType type) { switch (type) { - case JERSEY: - this.rtFacade = new JerseyRuntimeFacade(); - break; - case CXF: - this.rtFacade = new CxfRuntimeFacade(); - break; - default: - throw new RuntimeException("JAX-RS runtime type not supported: " + type); + case JERSEY: + this.rtFacade = new JerseyRuntimeFacade(); + break; + case CXF: + this.rtFacade = new CxfRuntimeFacade(); + break; + default: + throw new RuntimeException("JAX-RS runtime type not supported: " + type); } this.logRule(); this.log("parameterized runtime facade", type.toString()); @@ -115,24 +117,24 @@ public AbstractRuntimeTest(RuntimeFacadeType type) { public static List data() { /* - TODO Ideally the test suite runs twice using CXF and Jersey as runtime. - Unfortunately CXF has issues and throws errors if Jersey did run first. This - issues are addressed to CXF mailing list: users@cxf.apache.org - - Intermediate wise the runtime is selected from environment variable. Allowed configurations: - - org.odata4j.jaxrs.runtime = jersey - org.odata4j.jaxrs.runtime = cxf - org.odata4j.jaxrs.runtime = jersey, cxf // currently not supported by CXF - + * TODO Ideally the test suite runs twice using CXF and Jersey as runtime. + * Unfortunately CXF has issues and throws errors if Jersey did run first. This + * issues are addressed to CXF mailing list: users@cxf.apache.org + * + * Intermediate wise the runtime is selected from environment variable. Allowed + * configurations: + * + * org.odata4j.jaxrs.runtime = jersey + * org.odata4j.jaxrs.runtime = cxf + * org.odata4j.jaxrs.runtime = jersey, cxf // currently not supported by CXF + * */ Object[][] a; String value = System.getProperty(AbstractRuntimeTest.RUNTIME_ENVIRONMENT_PROPERTY); if (value == null) { a = new Object[][] { { RuntimeFacadeType.JERSEY } }; // default - } - else { + } else { StringTokenizer strt = new StringTokenizer(value, " ,;", false); a = new Object[strt.countTokens()][1]; for (int i = 0; strt.hasMoreTokens(); i++) { diff --git a/test-integration/src/test/java/org/odata4j/test/integration/CxfRuntimeFacade.java b/test-integration/src/test/java/org/odata4j/test/integration/CxfRuntimeFacade.java index 5152a96..b8428a9 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/CxfRuntimeFacade.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/CxfRuntimeFacade.java @@ -7,8 +7,8 @@ import java.util.Hashtable; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; import org.apache.http.Header; import org.apache.http.HttpEntity; @@ -105,12 +105,14 @@ public ResponseData getWebResource(String uri) { return this.getResource(ODataHttpMethod.GET, uri, null, null, null); } - private ResponseData getResource(ODataHttpMethod method, String uri, InputStream content, MediaType mediaType, Map headers) { + private ResponseData getResource(ODataHttpMethod method, String uri, InputStream content, MediaType mediaType, + Map headers) { String resource = ""; try { HttpClient httpClient = new DefaultHttpClient(); - if (System.getProperties().containsKey("http.proxyHost") && System.getProperties().containsKey("http.proxyPort")) { + if (System.getProperties().containsKey("http.proxyHost") + && System.getProperties().containsKey("http.proxyPort")) { // support proxy settings String hostName = System.getProperties().getProperty("http.proxyHost"); String hostPort = System.getProperties().getProperty("http.proxyPort"); @@ -122,40 +124,40 @@ private ResponseData getResource(ODataHttpMethod method, String uri, InputStream HttpUriRequest httpRequest; switch (method) { - case GET: - httpRequest = new HttpGet(uri); - break; - case DELETE: - httpRequest = new HttpDelete(uri); - break; - case PATCH: - HttpPost patch = new HttpPost(uri); - if (content != null) - patch.setEntity(new InputStreamEntity(content, -1)); - patch.setHeader(Headers.X_HTTP_METHOD, "PATCH"); - httpRequest = patch; - break; - case MERGE: - HttpPost merge = new HttpPost(uri); - if (content != null) - merge.setEntity(new InputStreamEntity(content, -1)); - merge.setHeader(Headers.X_HTTP_METHOD, "MERGE"); - httpRequest = merge; - break; - case PUT: - HttpPut put = new HttpPut(uri); - if (content != null) - put.setEntity(new InputStreamEntity(content, -1)); - httpRequest = put; - break; - case POST: - HttpPost post = new HttpPost(uri); - if (content != null) - post.setEntity(new InputStreamEntity(content, -1)); - httpRequest = post; - break; - default: - throw new RuntimeException("Unsupported method: " + method); + case GET: + httpRequest = new HttpGet(uri); + break; + case DELETE: + httpRequest = new HttpDelete(uri); + break; + case PATCH: + HttpPost patch = new HttpPost(uri); + if (content != null) + patch.setEntity(new InputStreamEntity(content, -1)); + patch.setHeader(Headers.X_HTTP_METHOD, "PATCH"); + httpRequest = patch; + break; + case MERGE: + HttpPost merge = new HttpPost(uri); + if (content != null) + merge.setEntity(new InputStreamEntity(content, -1)); + merge.setHeader(Headers.X_HTTP_METHOD, "MERGE"); + httpRequest = merge; + break; + case PUT: + HttpPut put = new HttpPut(uri); + if (content != null) + put.setEntity(new InputStreamEntity(content, -1)); + httpRequest = put; + break; + case POST: + HttpPost post = new HttpPost(uri); + if (content != null) + post.setEntity(new InputStreamEntity(content, -1)); + httpRequest = post; + break; + default: + throw new RuntimeException("Unsupported method: " + method); } if (headers != null) { @@ -169,8 +171,7 @@ private ResponseData getResource(ODataHttpMethod method, String uri, InputStream if (content != null) { httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, mediaType.toString()); } - if (method == ODataHttpMethod.GET) - { + if (method == ODataHttpMethod.GET) { httpRequest.addHeader(HttpHeaders.ACCEPT, mediaType.toString()); } } @@ -193,32 +194,38 @@ private ResponseData getResource(ODataHttpMethod method, String uri, InputStream } @Override - public ResponseData postWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData postWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.getResource(ODataHttpMethod.POST, uri, content, mediaType, headers); } @Override - public ResponseData putWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData putWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.getResource(ODataHttpMethod.PUT, uri, content, mediaType, headers); } @Override - public ResponseData mergeWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData mergeWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.getResource(ODataHttpMethod.MERGE, uri, content, mediaType, headers); } @Override - public ResponseData patchWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData patchWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.getResource(ODataHttpMethod.PATCH, uri, content, mediaType, headers); } @Override - public ResponseData getWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData getWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.getResource(ODataHttpMethod.GET, uri, content, mediaType, headers); } @Override - public ResponseData deleteWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData deleteWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.getResource(ODataHttpMethod.DELETE, uri, content, mediaType, headers); } } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/JerseyRuntimeFacade.java b/test-integration/src/test/java/org/odata4j/test/integration/JerseyRuntimeFacade.java index 34e9978..2febc05 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/JerseyRuntimeFacade.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/JerseyRuntimeFacade.java @@ -1,32 +1,27 @@ package org.odata4j.test.integration; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Map; -import java.util.Map.Entry; - -import javax.ws.rs.core.MediaType; - +import jakarta.ws.rs.client.*; +import jakarta.ws.rs.core.MediaType; +import org.glassfish.jersey.client.ClientResponse; import org.odata4j.consumer.ODataConsumer; import org.odata4j.consumer.behaviors.OClientBehavior; import org.odata4j.core.ODataConstants.Headers; import org.odata4j.core.ODataHttpMethod; import org.odata4j.core.Throwables; -import org.odata4j.format.FormatType; import org.odata4j.examples.jersey.consumer.ODataJerseyConsumer; import org.odata4j.examples.jersey.consumer.ODataJerseyConsumer.Builder; import org.odata4j.examples.jersey.producer.server.ODataJerseyServer; +import org.odata4j.format.FormatType; import org.odata4j.producer.resources.DefaultODataApplication; import org.odata4j.producer.resources.RootApplication; import org.odata4j.producer.server.ODataServer; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.container.filter.LoggingFilter; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Map; +import java.util.Map.Entry; public class JerseyRuntimeFacade implements RuntimeFacade { @@ -50,8 +45,8 @@ public ODataServer startODataServer(String baseUri) { @Override public ODataServer createODataServer(String baseUri) { - return new ODataJerseyServer(baseUri, DefaultODataApplication.class, RootApplication.class) - .addJerseyRequestFilter(LoggingFilter.class); // log all requests + return new ODataJerseyServer(baseUri, DefaultODataApplication.class, RootApplication.class); + // .addJerseyRequestFilter(ClientLoggingFilter.class); // log all requests } @Override @@ -71,18 +66,20 @@ public ODataConsumer createODataConsumer(String endpointUri, FormatType format, @Override public ResponseData getWebResource(String uri) { - WebResource webResource = new Client().resource(uri); + WebTarget webResource = ClientBuilder.newClient().target(uri); - ClientResponse response = webResource.get(ClientResponse.class); - return new ResponseData(response.getStatus(), response.getEntity(String.class)); + ClientResponse response = webResource.request().get(ClientResponse.class); + return new ResponseData(response.getStatus(), response.readEntity(String.class)); } @Override - public ResponseData postWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData postWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.requestWebResource(ODataHttpMethod.POST, uri, content, mediaType, headers); } - public ResponseData putWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData putWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.requestWebResource(ODataHttpMethod.PUT, uri, content, mediaType, headers); } @@ -90,20 +87,20 @@ public ResponseData putWebResource(String uri, InputStream content, MediaType me public ResponseData acceptAndReturn(String uri, MediaType mediaType) { uri = uri.replace(" ", "%20"); - WebResource webResource = new Client().resource(uri); + WebTarget webResource = ClientBuilder.newClient().target(uri); - ClientResponse response = webResource.accept(mediaType).get(ClientResponse.class); - String body = response.getEntity(String.class); + ClientResponse response = webResource.request(mediaType).get(ClientResponse.class); + String body = response.readEntity(String.class); return new ResponseData(response.getStatus(), body); } @Override public ResponseData getWebResource(String uri, String accept) { - WebResource webResource = new Client().resource(uri); + WebTarget webResource = ClientBuilder.newClient().target(uri); - ClientResponse response = webResource.accept(accept).get(ClientResponse.class); - String body = response.getEntity(String.class); + ClientResponse response = webResource.request(accept).get(ClientResponse.class); + String body = response.readEntity(String.class); return new ResponseData(response.getStatus(), body); } @@ -111,74 +108,75 @@ public ResponseData getWebResource(String uri, String accept) { @Override public void accept(String uri, MediaType mediaType) { uri = uri.replace(" ", "%20"); - WebResource webResource = new Client().resource(uri); - webResource.accept(mediaType); + WebTarget webResource = ClientBuilder.newClient().target(uri); + webResource.request(mediaType); } @Override - public ResponseData mergeWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData mergeWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.requestWebResource(ODataHttpMethod.MERGE, uri, content, mediaType, headers); } @Override - public ResponseData patchWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData patchWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.requestWebResource(ODataHttpMethod.PATCH, uri, content, mediaType, headers); } @Override - public ResponseData getWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData getWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.requestWebResource(ODataHttpMethod.GET, uri, content, mediaType, headers); } @Override - public ResponseData deleteWebResource(String uri, InputStream content, MediaType mediaType, Map headers) { + public ResponseData deleteWebResource(String uri, InputStream content, MediaType mediaType, + Map headers) { return this.requestWebResource(ODataHttpMethod.DELETE, uri, content, mediaType, headers); } - private ResponseData requestWebResource(ODataHttpMethod method, String uri, InputStream content, MediaType mediaType, Map headers) { - Client client = new Client(); - WebResource.Builder webResource = client.resource(uri).type(mediaType); + private ResponseData requestWebResource(ODataHttpMethod method, String uri, InputStream content, MediaType mediaType, + Map headers) { + Client client = ClientBuilder.newClient(); + Invocation.Builder webResource = client.target(uri).request(mediaType); int statusCode; String entity = ""; - try { - if (headers != null) { - for (Entry entry : headers.entrySet()) { - webResource = webResource.header(entry.getKey(), entry.getValue()); - } + if (headers != null) { + for (Entry entry : headers.entrySet()) { + webResource = webResource.header(entry.getKey(), entry.getValue()); } + } - ClientResponse response; - switch (method) { + ClientResponse response; + switch (method) { case DELETE: - response = webResource.delete(ClientResponse.class, content); + response = webResource.delete(ClientResponse.class); break; case PATCH: webResource = webResource.header(Headers.X_HTTP_METHOD, "PATCH"); - response = webResource.post(ClientResponse.class, content); + response = webResource.post(Entity.entity(content, mediaType), ClientResponse.class); break; case GET: response = webResource.get(ClientResponse.class); break; case MERGE: webResource = webResource.header(Headers.X_HTTP_METHOD, "MERGE"); - response = webResource.post(ClientResponse.class, content); + response = webResource.post(Entity.entity(content, mediaType), ClientResponse.class); break; case POST: - response = webResource.post(ClientResponse.class, content); + response = webResource.post(Entity.entity(content, mediaType), ClientResponse.class); break; case PUT: - response = webResource.put(ClientResponse.class, content); + response = webResource.put(Entity.entity(content, mediaType), ClientResponse.class); break; default: throw new RuntimeException("Unsupported http method: " + method); - } - - statusCode = response.getStatus(); - entity = response.getEntity(String.class); - } catch (UniformInterfaceException ex) { - statusCode = ex.getResponse().getStatus(); } + + statusCode = response.getStatus(); + entity = response.readEntity(String.class); return new ResponseData(statusCode, entity); } -} +} \ No newline at end of file diff --git a/test-integration/src/test/java/org/odata4j/test/integration/PortConflictTest.java b/test-integration/src/test/java/org/odata4j/test/integration/PortConflictTest.java new file mode 100644 index 0000000..c784b2c --- /dev/null +++ b/test-integration/src/test/java/org/odata4j/test/integration/PortConflictTest.java @@ -0,0 +1,39 @@ +package org.odata4j.test.integration; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class PortConflictTest extends AbstractIntegrationTest { + + public PortConflictTest(RuntimeFacadeType type) { + super(type); + } + + @Override + protected void registerODataProducer() throws Exception { + // No producer needed for this test + } + + @Override + protected void startClient() throws Exception { + // No client needed for this test + } + + @Override + protected void stopClient() throws Exception { + // No client needed for this test + } + + @Test + public void testUniquePortPerInstance() throws Exception { + // Create another instance to verify different ports + PortConflictTest otherTest = new PortConflictTest(RuntimeFacadeType.JERSEY); + + // Verify that instances get different BASE_URIs (and thus different ports) + assertNotEquals("Different test instances should have different BASE_URIs", + this.BASE_URI, otherTest.BASE_URI); + + System.out.println("This instance BASE_URI: " + this.BASE_URI); + System.out.println("Other instance BASE_URI: " + otherTest.BASE_URI); + } +} diff --git a/test-integration/src/test/java/org/odata4j/test/integration/RuntimeFacade.java b/test-integration/src/test/java/org/odata4j/test/integration/RuntimeFacade.java index 82ce7bf..009acfb 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/RuntimeFacade.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/RuntimeFacade.java @@ -3,7 +3,7 @@ import java.io.InputStream; import java.util.Map; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.odata4j.consumer.ODataConsumer; import org.odata4j.consumer.behaviors.OClientBehavior; @@ -28,16 +28,20 @@ public interface RuntimeFacade { public ResponseData getWebResource(String uri); - public ResponseData postWebResource(String uri, InputStream content, MediaType mediaType, Map headers); + public ResponseData postWebResource(String uri, InputStream content, MediaType mediaType, + Map headers); public ResponseData putWebResource(String uri, InputStream content, MediaType mediaType, Map headers); - public ResponseData mergeWebResource(String uri, InputStream content, MediaType mediaType, Map headers); + public ResponseData mergeWebResource(String uri, InputStream content, MediaType mediaType, + Map headers); - public ResponseData patchWebResource(String uri, InputStream content, MediaType mediaType, Map headers); + public ResponseData patchWebResource(String uri, InputStream content, MediaType mediaType, + Map headers); public ResponseData getWebResource(String uri, InputStream content, MediaType mediaType, Map headers); - public ResponseData deleteWebResource(String uri, InputStream content, MediaType mediaType, Map headers); + public ResponseData deleteWebResource(String uri, InputStream content, MediaType mediaType, + Map headers); } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/consumer/BasicAuthenticationTest.java b/test-integration/src/test/java/org/odata4j/test/integration/consumer/BasicAuthenticationTest.java index 0dc509e..617c2aa 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/consumer/BasicAuthenticationTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/consumer/BasicAuthenticationTest.java @@ -3,14 +3,16 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.junit.matchers.JUnitMatchers.containsString; -import org.eclipse.jetty.http.security.Constraint; -import org.eclipse.jetty.http.security.Password; +import org.eclipse.jetty.util.security.Constraint; +import org.eclipse.jetty.util.security.Password; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.security.SecurityHandler; +import org.eclipse.jetty.security.UserStore; import org.joda.time.LocalDateTime; import org.junit.Test; import org.odata4j.consumer.ODataConsumer; @@ -24,6 +26,8 @@ import org.odata4j.exceptions.NotImplementedException; import org.odata4j.producer.resources.DefaultODataProducerProvider; import org.odata4j.test.integration.AbstractODataConsumerTest; +import org.odata4j.test.integration.AbstractRuntimeTest.RuntimeFacadeType; +import org.junit.Assert; import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.BasicAuthenticator; @@ -82,8 +86,13 @@ private ConstraintMapping mapping(Constraint constraint) { } private HashLoginService loginService() { - HashLoginService loginService = new HashLoginService(); - loginService.update(USERNAME, new Password(PASSWORD), new String[] { ROLE }); + // HashLoginService loginService = new HashLoginService(); + // loginService.update(USERNAME, new Password(PASSWORD), new String[] { ROLE }); + // return loginService; + HashLoginService loginService = new HashLoginService("MyRealm"); + UserStore userStore = new UserStore(); + userStore.addUser(USERNAME, new Password(PASSWORD), new String[] { ROLE }); + loginService.setUserStore(userStore); return loginService; } @@ -103,7 +112,7 @@ public void unauthorizedConsumerIsRejected() throws Exception { ODataConsumer unauthorizedConsumer = rtFacade.createODataConsumer(BASE_URI, format); try { unauthorizedConsumer.getEntities("Persons").execute(); - fail(); + Assert.fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), containsString("Unauthorized")); } @@ -115,17 +124,18 @@ public void getEntity() throws Exception { assertThat(entity, notNullValue()); } - @Test(expected=NotImplementedException.class) + @Test(expected = NotImplementedException.class) public void createEntity() throws Exception { OProperty personId = OProperties.int32("PersonId", Integer.valueOf(4)); OProperty name = OProperties.string("Name", "Stephanie Spring"); OProperty emailAddress = OProperties.string("EmailAddress", "st.spring@mail-provider.com"); OProperty birthDay = OProperties.datetime("BirthDay", new LocalDateTime(1979, 4, 9, 0, 0)); - assertThat(consumer.createEntity("Persons").properties(personId, name, emailAddress, birthDay).execute(), notNullValue()); + assertThat(consumer.createEntity("Persons").properties(personId, name, emailAddress, birthDay).execute(), + notNullValue()); } - @Test(expected=NotImplementedException.class) + @Test(expected = NotImplementedException.class) public void updateEntity() throws Exception { OProperty newEmailAddress = OProperties.string("EmailAddress", "walter.winter@new-company.com"); @@ -133,7 +143,7 @@ public void updateEntity() throws Exception { consumer.updateEntity(entity).properties(newEmailAddress).execute(); } - @Test(expected=NotImplementedException.class) + @Test(expected = NotImplementedException.class) public void deleteEntity() throws Exception { consumer.deleteEntity("Persons", Integer.valueOf(3)).execute(); } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/consumer/ErrorTest.java b/test-integration/src/test/java/org/odata4j/test/integration/consumer/ErrorTest.java index fa4697b..f9913af 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/consumer/ErrorTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/consumer/ErrorTest.java @@ -4,8 +4,8 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.Response.StatusType; +import jakarta.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.Response.StatusType; import org.junit.After; import org.junit.Test; diff --git a/test-integration/src/test/java/org/odata4j/test/integration/function/FunctionImportTest.java b/test-integration/src/test/java/org/odata4j/test/integration/function/FunctionImportTest.java index e4c1356..47ce7eb 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/function/FunctionImportTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/function/FunctionImportTest.java @@ -14,8 +14,8 @@ import java.util.Hashtable; import java.util.List; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response.Status; import javax.xml.parsers.ParserConfigurationException; import org.core4j.Enumerable; @@ -54,9 +54,10 @@ public FunctionImportTest() { } /* - public FunctionImportTest(RuntimeFacadeType type) { - super(type); - }*/ + * public FunctionImportTest(RuntimeFacadeType type) { + * super(type); + * } + */ private static ArrayList formats; static { @@ -97,12 +98,15 @@ public TestCase(String parameterName, String valueLiteral, String valueString, E FunctionImportTest.testCases.add(new TestCase("p1", "X'1F'", "0x1f", EdmSimpleType.BINARY)); FunctionImportTest.testCases.add(new TestCase("p2", "true", "true", EdmSimpleType.BOOLEAN)); FunctionImportTest.testCases.add(new TestCase("p3", "1", "1", EdmSimpleType.BYTE)); - FunctionImportTest.testCases.add(new TestCase("p4", "datetime'2010-12-12T23:44:57.123'", "2010-12-12T23:44:57.123", EdmSimpleType.DATETIME)); + FunctionImportTest.testCases.add( + new TestCase("p4", "datetime'2010-12-12T23:44:57.123'", "2010-12-12T23:44:57.123", EdmSimpleType.DATETIME)); FunctionImportTest.testCases.add(new TestCase("p5", "22.5m", "22.5", EdmSimpleType.DECIMAL)); FunctionImportTest.testCases.add(new TestCase("p6", "1d", "1.0", EdmSimpleType.DOUBLE)); FunctionImportTest.testCases.add(new TestCase("p7", "1f", "1.0", EdmSimpleType.SINGLE)); - FunctionImportTest.testCases.add(new TestCase("p8", "datetimeoffset'2012-12-12T22:07:44.123Z'", "2012-12-12T22:07:44.123Z", EdmSimpleType.DATETIMEOFFSET)); - FunctionImportTest.testCases.add(new TestCase("p9", "guid'11111111-1111-1111-1111-111111111111'", "11111111-1111-1111-1111-111111111111", EdmSimpleType.GUID)); + FunctionImportTest.testCases.add(new TestCase("p8", "datetimeoffset'2012-12-12T22:07:44.123Z'", + "2012-12-12T22:07:44.123Z", EdmSimpleType.DATETIMEOFFSET)); + FunctionImportTest.testCases.add(new TestCase("p9", "guid'11111111-1111-1111-1111-111111111111'", + "11111111-1111-1111-1111-111111111111", EdmSimpleType.GUID)); FunctionImportTest.testCases.add(new TestCase("p10", "1", "1", EdmSimpleType.INT16)); FunctionImportTest.testCases.add(new TestCase("p11", "1", "1", EdmSimpleType.INT32)); FunctionImportTest.testCases.add(new TestCase("p12", "1L", "1", EdmSimpleType.INT64)); @@ -115,14 +119,14 @@ private String formatQuery(FormatType type) { String query; switch (type) { - case ATOM: - query = "$format=atom"; - break; - case JSON: - query = "$format=json"; - break; - default: - throw new RuntimeException("Unknown Format Type: " + type); + case ATOM: + query = "$format=atom"; + break; + case JSON: + query = "$format=json"; + break; + default: + throw new RuntimeException("Unknown Format Type: " + type); } return query; @@ -172,23 +176,24 @@ public void testFunctionReturnStringWithAllParameter() throws XpathException, SA String query = "?p1=X'1F'&p2=true&p3=1&p4=datetime'2010-12-12T23:44:57'&p5=22.5m&p6=1d&p7=1f&p8=datetimeoffset'2012-12-12T22:07:44Z'&p9=guid'11111111-1111-1111-1111-111111111111'&p10=1&p11=1&p12=1L&p13=1&p14='hugo'&p15=time'PT10H30M'"; for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING + query + "&" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING + query + "&" + this.formatQuery(format)); String resource = responseData.getEntity(); assertEquals(format.toString(), 200, responseData.getStatusCode()); assertNotNull(format.toString(), this.mockProducer.getQueryParameter()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnString", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnString/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnString", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnString/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } @@ -197,23 +202,25 @@ public void testFunctionReturnStringWithAllParameter() throws XpathException, SA @Test public void testFunctionReturnBoolean() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_BOOLEAN + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade + .getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_BOOLEAN + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); assertEquals(format.toString(), 200, responseData.getStatusCode()); assertNotNull(format.toString(), this.mockProducer.getQueryParameter()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnBoolean", resource); - assertXpathEvaluatesTo(Boolean.toString(FunctionImportProducerMock.BOOLEAN_VALUE), "/d:TestFunctionReturnBoolean/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_BOOLEAN)); - assertTrue(format.toString(), resource.contains(Boolean.toString(FunctionImportProducerMock.BOOLEAN_VALUE))); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnBoolean", resource); + assertXpathEvaluatesTo(Boolean.toString(FunctionImportProducerMock.BOOLEAN_VALUE), + "/d:TestFunctionReturnBoolean/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_BOOLEAN)); + assertTrue(format.toString(), resource.contains(Boolean.toString(FunctionImportProducerMock.BOOLEAN_VALUE))); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -236,7 +243,8 @@ public void testFunctionReturnString() throws XpathException, IOException, SAXEx String query = "?" + testCase.parameterName + "=" + testCase.valueLiteral; for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING + query + "&" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING + query + "&" + this.formatQuery(format)); String resource = responseData.getEntity(); String msg = format + " | TestCase: " + testCase.toString(); @@ -245,27 +253,31 @@ public void testFunctionReturnString() throws XpathException, IOException, SAXEx assertNotNull(msg, this.mockProducer.getQueryParameter()); assertTrue(msg, this.mockProducer.getQueryParameter().containsKey(testCase.parameterName)); - assertEquals(msg, testCase.parameterName, this.mockProducer.getQueryParameter().get(testCase.parameterName).getName()); + assertEquals(msg, testCase.parameterName, + this.mockProducer.getQueryParameter().get(testCase.parameterName).getName()); assertEquals(msg, testCase.type, this.mockProducer.getQueryParameter().get(testCase.parameterName).getType()); - assertEquals(msg, testCase.valueString, OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get(testCase.parameterName).getValue())); + assertEquals(msg, testCase.valueString, OSimpleObjects + .getValueDisplayString(this.mockProducer.getQueryParameter().get(testCase.parameterName).getValue())); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnString", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnString/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnString", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnString/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } } - protected void testFunctionConsumer(String functionName, EdmType expectedType, int nExpected, Predicate1 alsoTrue) { + protected void testFunctionConsumer(String functionName, EdmType expectedType, int nExpected, + Predicate1 alsoTrue) { for (FormatType format : FunctionImportTest.formats) { if (format.equals(FormatType.ATOM)) { continue; @@ -298,23 +310,25 @@ public boolean apply(OObject t) { @Test public void testFunctionReturnInt16() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_INT16 + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade + .getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_INT16 + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); assertEquals(format.toString(), 200, responseData.getStatusCode()); assertNotNull(format.toString(), this.mockProducer.getQueryParameter()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnInt16", resource); - assertXpathEvaluatesTo(Integer.toString(FunctionImportProducerMock.INT16_VALUE), "/d:TestFunctionReturnInt16/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_INT16)); - assertTrue(format.toString(), resource.contains(Integer.toString(FunctionImportProducerMock.INT16_VALUE))); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnInt16", resource); + assertXpathEvaluatesTo(Integer.toString(FunctionImportProducerMock.INT16_VALUE), + "/d:TestFunctionReturnInt16/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_INT16)); + assertTrue(format.toString(), resource.contains(Integer.toString(FunctionImportProducerMock.INT16_VALUE))); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -335,7 +349,8 @@ public boolean apply(OObject t) { public void testFunctionReturnStringWithNoQueryParameter() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade + .getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); assertEquals(format.toString(), 200, responseData.getStatusCode()); @@ -361,16 +376,16 @@ public void testFunctionReturnStringWithNoQueryParameter() throws XpathException assertFalse(format.toString(), this.mockProducer.getQueryParameter().containsKey("p16")); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnString", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnString/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnString", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnString/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } @@ -380,24 +395,27 @@ public void testFunctionReturnStringWithNoQueryParameter() throws XpathException public void testFunctionReturnEntity() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_ENTITY + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade + .getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_ENTITY + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); this.logger.debug(resource); assertEquals(format.toString(), 200, responseData.getStatusCode()); switch (format) { - case ATOM: - assertXpathEvaluatesTo("RefScenario.Employee", "/g:entry/g:category/@term", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_NAME, "/g:entry/g:content/m:properties/d:EmployeeName/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_ID, "/g:entry/g:content/m:properties/d:EmployeeId/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_NAME)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_ID)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathEvaluatesTo("RefScenario.Employee", "/g:entry/g:category/@term", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_NAME, + "/g:entry/g:content/m:properties/d:EmployeeName/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_ID, + "/g:entry/g:content/m:properties/d:EmployeeId/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_NAME)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_ID)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -405,12 +423,14 @@ public void testFunctionReturnEntity() throws XpathException, IOException, SAXEx @Test public void testFunctionReturnEntityConsumer() { - testFunctionConsumer(MetadataUtil.TEST_FUNCTION_RETURN_ENTITY, mockProducer.getMetadata().findEdmEntitySet("Employees").getType(), 1, + testFunctionConsumer(MetadataUtil.TEST_FUNCTION_RETURN_ENTITY, + mockProducer.getMetadata().findEdmEntitySet("Employees").getType(), 1, new Predicate1() { @Override public boolean apply(OObject t) { OEntity e = (OEntity) t; - return e.getProperty("EmployeeName", String.class).getValue().equals(FunctionImportProducerMock.EMPLOYEE_NAME) && + return e.getProperty("EmployeeName", String.class).getValue() + .equals(FunctionImportProducerMock.EMPLOYEE_NAME) && e.getProperty("EmployeeId", String.class).getValue().equals(FunctionImportProducerMock.EMPLOYEE_ID); } }); @@ -420,29 +440,33 @@ public boolean apply(OObject t) { public void testFunctionReturnComplexType() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COMPLEX_TYPE + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COMPLEX_TYPE + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); this.logger.debug(resource); assertEquals(format.toString(), 200, responseData.getStatusCode()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnComplexType", resource); - assertXpathEvaluatesTo("RefScenario.c_Location", "/d:TestFunctionReturnComplexType/@m:type", resource); - assertXpathEvaluatesTo("RefScenario.c_City", "/d:TestFunctionReturnComplexType/d:City/@m:type", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.POSTAL_CODE, "/d:TestFunctionReturnComplexType/d:City/d:PostalCode/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.CITY, "/d:TestFunctionReturnComplexType/d:City/d:CityName/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.COUNTRY, "/d:TestFunctionReturnComplexType/d:Country/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_COMPLEX_TYPE)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.CITY)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COUNTRY)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.POSTAL_CODE)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnComplexType", resource); + assertXpathEvaluatesTo("RefScenario.c_Location", "/d:TestFunctionReturnComplexType/@m:type", resource); + assertXpathEvaluatesTo("RefScenario.c_City", "/d:TestFunctionReturnComplexType/d:City/@m:type", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.POSTAL_CODE, + "/d:TestFunctionReturnComplexType/d:City/d:PostalCode/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.CITY, + "/d:TestFunctionReturnComplexType/d:City/d:CityName/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.COUNTRY, + "/d:TestFunctionReturnComplexType/d:Country/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_COMPLEX_TYPE)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.CITY)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COUNTRY)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.POSTAL_CODE)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -458,11 +482,16 @@ public void testFunctionReturnComplexTypeConsumer() { @Override public boolean apply(OObject t) { OComplexObject e = (OComplexObject) t; - // weird that e.getProperty("City") returns a property list and not a complex object. - // and furthermore...why is List> used...there should be a PropertyBag abstraction no? - OComplexObject city = OComplexObjects.create(mockProducer.getMetadata().findEdmComplexType(FunctionImportProducerMock.COMPLEY_TYPE_NAME_CITY), e.getProperty("City", List.class).getValue()); + // weird that e.getProperty("City") returns a property list and not a complex + // object. + // and furthermore...why is List> used...there should be a + // PropertyBag abstraction no? + OComplexObject city = OComplexObjects.create( + mockProducer.getMetadata().findEdmComplexType(FunctionImportProducerMock.COMPLEY_TYPE_NAME_CITY), + e.getProperty("City", List.class).getValue()); return e.getProperty("Country", String.class).getValue().equals(FunctionImportProducerMock.COUNTRY) - && city.getProperty("PostalCode", String.class).getValue().equals(FunctionImportProducerMock.POSTAL_CODE) + && city.getProperty("PostalCode", String.class).getValue() + .equals(FunctionImportProducerMock.POSTAL_CODE) && city.getProperty("CityName", String.class).getValue().equals(FunctionImportProducerMock.CITY); } }); @@ -471,25 +500,28 @@ public boolean apply(OObject t) { @Test public void testFunctionReturnCollectionString() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_STRING + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_STRING + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); this.logger.debug(resource); assertEquals(format.toString(), 200, responseData.getStatusCode()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnCollectionString", resource); - assertXpathNotExists("/d:TestFunctionReturnCollectionString/d:element/@m:type", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.COLLECTION_STRING1, "/d:TestFunctionReturnCollectionString/d:element[1]/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.COLLECTION_STRING2, "/d:TestFunctionReturnCollectionString/d:element[2]/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COLLECTION_STRING1)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COLLECTION_STRING2)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnCollectionString", resource); + assertXpathNotExists("/d:TestFunctionReturnCollectionString/d:element/@m:type", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.COLLECTION_STRING1, + "/d:TestFunctionReturnCollectionString/d:element[1]/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.COLLECTION_STRING2, + "/d:TestFunctionReturnCollectionString/d:element[2]/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COLLECTION_STRING1)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COLLECTION_STRING2)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -514,25 +546,30 @@ public boolean apply(OObject t) { @Test public void testFunctionReturnCollectionDouble() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_DOUBLE + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_DOUBLE + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); this.logger.debug(resource); assertEquals(format.toString(), 200, responseData.getStatusCode()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnCollectionDouble", resource); - assertXpathNotExists("/d:TestFunctionReturnCollectionDouble/d:element/@m:type", resource); - assertXpathEvaluatesTo(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE1), "/d:TestFunctionReturnCollectionDouble/d:element[1]/text()", resource); - assertXpathEvaluatesTo(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE2), "/d:TestFunctionReturnCollectionDouble/d:element[2]/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE1))); - assertTrue(format.toString(), resource.contains(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE2))); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnCollectionDouble", resource); + assertXpathNotExists("/d:TestFunctionReturnCollectionDouble/d:element/@m:type", resource); + assertXpathEvaluatesTo(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE1), + "/d:TestFunctionReturnCollectionDouble/d:element[1]/text()", resource); + assertXpathEvaluatesTo(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE2), + "/d:TestFunctionReturnCollectionDouble/d:element[2]/text()", resource); + break; + case JSON: + assertTrue(format.toString(), + resource.contains(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE1))); + assertTrue(format.toString(), + resource.contains(Double.toString(FunctionImportProducerMock.COLLECTION_DOUBLE2))); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -549,32 +586,42 @@ public void testFunctionReturnCollectionDoubleConsumer() { @Test public void testFunctionReturnCollectionComplexType() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_COMPLEX_TYPE + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_COMPLEX_TYPE + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); this.logger.debug(resource); assertEquals(format.toString(), 200, responseData.getStatusCode()); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnCollectionComplexType", resource); - assertXpathEvaluatesTo("RefScenario.c_Location", "/d:TestFunctionReturnCollectionComplexType/d:element/@m:type", resource); - assertXpathEvaluatesTo("RefScenario.c_City", "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/@m:type", resource); - assertXpathEvaluatesTo("RefScenario.c_City", "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/@m:type", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.CITY, "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/d:CityName/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.CITY, "/d:TestFunctionReturnCollectionComplexType/d:element[2]/d:City/d:CityName/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.POSTAL_CODE, "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/d:PostalCode/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.POSTAL_CODE, "/d:TestFunctionReturnCollectionComplexType/d:element[2]/d:City/d:PostalCode/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.COUNTRY, "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:Country", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.COUNTRY, "/d:TestFunctionReturnCollectionComplexType/d:element[2]/d:Country", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COUNTRY)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.POSTAL_CODE)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.CITY)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnCollectionComplexType", resource); + assertXpathEvaluatesTo("RefScenario.c_Location", + "/d:TestFunctionReturnCollectionComplexType/d:element/@m:type", resource); + assertXpathEvaluatesTo("RefScenario.c_City", + "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/@m:type", resource); + assertXpathEvaluatesTo("RefScenario.c_City", + "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/@m:type", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.CITY, + "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/d:CityName/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.CITY, + "/d:TestFunctionReturnCollectionComplexType/d:element[2]/d:City/d:CityName/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.POSTAL_CODE, + "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:City/d:PostalCode/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.POSTAL_CODE, + "/d:TestFunctionReturnCollectionComplexType/d:element[2]/d:City/d:PostalCode/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.COUNTRY, + "/d:TestFunctionReturnCollectionComplexType/d:element[1]/d:Country", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.COUNTRY, + "/d:TestFunctionReturnCollectionComplexType/d:element[2]/d:Country", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.COUNTRY)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.POSTAL_CODE)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.CITY)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -591,27 +638,30 @@ public void testFunctionReturnCollectionComplexTypeConsumer() { @Test public void testFunctionReturnCollectionEntityType() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = this.rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_ENTITY + "?" + this.formatQuery(format)); + ResponseData responseData = this.rtFacade.getWebResource( + endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_COLLECTION_ENTITY + "?" + this.formatQuery(format)); String resource = responseData.getEntity(); this.logger.debug(resource); assertEquals(format.toString(), 200, responseData.getStatusCode()); switch (format) { - case ATOM: - assertXpathExists("/g:feed", resource); - assertXpathEvaluatesTo("RefScenario.Employee", "/g:feed/g:entry/g:category/@term", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_ID, "/g:feed/g:entry/g:content/m:properties/d:EmployeeId/text()", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_NAME, "/g:feed/g:entry/g:content/m:properties/d:EmployeeName/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains("\"results\" : [")); - assertTrue(format.toString(), resource.contains("\"__metadata\" : {")); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_NAME)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_ID)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/g:feed", resource); + assertXpathEvaluatesTo("RefScenario.Employee", "/g:feed/g:entry/g:category/@term", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_ID, + "/g:feed/g:entry/g:content/m:properties/d:EmployeeId/text()", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.EMPLOYEE_NAME, + "/g:feed/g:entry/g:content/m:properties/d:EmployeeName/text()", resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains("\"results\" : [")); + assertTrue(format.toString(), resource.contains("\"__metadata\" : {")); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_NAME)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.EMPLOYEE_ID)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -627,7 +677,8 @@ public void testFunctionReturnCollectionEntityTypeConsumer() { @Override public boolean apply(OObject t) { OEntity e = (OEntity) t; - return e.getProperty("EmployeeName", String.class).getValue().equals(FunctionImportProducerMock.EMPLOYEE_NAME) + return e.getProperty("EmployeeName", String.class).getValue() + .equals(FunctionImportProducerMock.EMPLOYEE_NAME) && e.getProperty("EmployeeId", String.class).getValue().equals(FunctionImportProducerMock.EMPLOYEE_ID); } }); @@ -636,7 +687,8 @@ public boolean apply(OObject t) { @Test public void testFunctionReturnEntitySet() throws Exception { for (FormatType format : FunctionImportTest.formats) { - ResponseData responseData = rtFacade.getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_ENTITYSET + "?" + formatQuery(format)); + ResponseData responseData = rtFacade + .getWebResource(endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_ENTITYSET + "?" + formatQuery(format)); logger.debug(responseData.getEntity()); assertEquals(format.toString(), Status.OK.getStatusCode(), responseData.getStatusCode()); } @@ -646,7 +698,8 @@ public void testFunctionReturnEntitySet() throws Exception { public void testFunctionReturnStringPost() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { String param = "p1='abc'"; - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_POST + "?" + param + "&" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_POST + "?" + param + "&" + + this.formatQuery(format); ResponseData responseData = this.rtFacade.postWebResource(uri, null, null, null); String resource = responseData.getEntity(); @@ -656,19 +709,21 @@ public void testFunctionReturnStringPost() throws XpathException, IOException, S assertEquals(format.toString(), "p1", this.mockProducer.getQueryParameter().get("p1").getName()); assertEquals(format.toString(), EdmSimpleType.STRING, this.mockProducer.getQueryParameter().get("p1").getType()); - assertEquals(format.toString(), "abc", OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); + assertEquals(format.toString(), "abc", + OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnStringPost", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringPost/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_POST)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnStringPost", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringPost/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_POST)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -677,7 +732,8 @@ public void testFunctionReturnStringPost() throws XpathException, IOException, S public void testFunctionReturnStringGet() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { String param = "p1='abc'"; - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_GET + "?" + param + "&" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_GET + "?" + param + "&" + + this.formatQuery(format); ResponseData responseData = this.rtFacade.getWebResource(uri, null, null, null); String resource = responseData.getEntity(); @@ -690,19 +746,21 @@ public void testFunctionReturnStringGet() throws XpathException, IOException, SA assertEquals(format.toString(), "p1", this.mockProducer.getQueryParameter().get("p1").getName()); assertEquals(format.toString(), EdmSimpleType.STRING, this.mockProducer.getQueryParameter().get("p1").getType()); - assertEquals(format.toString(), "abc", OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); - + assertEquals(format.toString(), "abc", + OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); + switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnStringGet", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringGet/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_GET)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnStringGet", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringGet/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_GET)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -711,7 +769,8 @@ public void testFunctionReturnStringGet() throws XpathException, IOException, SA public void testFunctionReturnStringMerge() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { String param = "p1='abc'"; - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_MERGE + "?" + param + "&" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_MERGE + "?" + param + "&" + + this.formatQuery(format); ResponseData responseData = this.rtFacade.mergeWebResource(uri, null, null, null); String resource = responseData.getEntity(); @@ -721,19 +780,21 @@ public void testFunctionReturnStringMerge() throws XpathException, IOException, assertEquals(format.toString(), "p1", this.mockProducer.getQueryParameter().get("p1").getName()); assertEquals(format.toString(), EdmSimpleType.STRING, this.mockProducer.getQueryParameter().get("p1").getType()); - assertEquals(format.toString(), "abc", OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); + assertEquals(format.toString(), "abc", + OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnStringMerge", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringMerge/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_MERGE)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnStringMerge", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringMerge/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_MERGE)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -742,7 +803,8 @@ public void testFunctionReturnStringMerge() throws XpathException, IOException, public void testFunctionReturnStringPut() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { String param = "p1='abc'"; - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_PUT + "?" + param + "&" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_PUT + "?" + param + "&" + + this.formatQuery(format); ResponseData responseData = this.rtFacade.putWebResource(uri, null, null, null); String resource = responseData.getEntity(); @@ -752,19 +814,21 @@ public void testFunctionReturnStringPut() throws XpathException, IOException, SA assertEquals(format.toString(), "p1", this.mockProducer.getQueryParameter().get("p1").getName()); assertEquals(format.toString(), EdmSimpleType.STRING, this.mockProducer.getQueryParameter().get("p1").getType()); - assertEquals(format.toString(), "abc", OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); + assertEquals(format.toString(), "abc", + OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnStringPut", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringPut/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_PUT)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnStringPut", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringPut/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_PUT)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -773,7 +837,8 @@ public void testFunctionReturnStringPut() throws XpathException, IOException, SA public void testFunctionReturnStringDelete() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { String param = "p1='abc'"; - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_DELETE + "?" + param + "&" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_DELETE + "?" + param + "&" + + this.formatQuery(format); ResponseData responseData = this.rtFacade.deleteWebResource(uri, null, null, null); String resource = responseData.getEntity(); @@ -783,19 +848,21 @@ public void testFunctionReturnStringDelete() throws XpathException, IOException, assertEquals(format.toString(), "p1", this.mockProducer.getQueryParameter().get("p1").getName()); assertEquals(format.toString(), EdmSimpleType.STRING, this.mockProducer.getQueryParameter().get("p1").getType()); - assertEquals(format.toString(), "abc", OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); + assertEquals(format.toString(), "abc", + OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnStringDelete", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringDelete/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_DELETE)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnStringDelete", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringDelete/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_DELETE)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -804,7 +871,8 @@ public void testFunctionReturnStringDelete() throws XpathException, IOException, public void testFunctionReturnStringPatch() throws XpathException, IOException, SAXException { for (FormatType format : FunctionImportTest.formats) { String param = "p1='abc'"; - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_PATCH + "?" + param + "&" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_PATCH + "?" + param + "&" + + this.formatQuery(format); ResponseData responseData = this.rtFacade.patchWebResource(uri, null, null, null); String resource = responseData.getEntity(); @@ -814,19 +882,21 @@ public void testFunctionReturnStringPatch() throws XpathException, IOException, assertEquals(format.toString(), "p1", this.mockProducer.getQueryParameter().get("p1").getName()); assertEquals(format.toString(), EdmSimpleType.STRING, this.mockProducer.getQueryParameter().get("p1").getType()); - assertEquals(format.toString(), "abc", OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); + assertEquals(format.toString(), "abc", + OSimpleObjects.getValueDisplayString(this.mockProducer.getQueryParameter().get("p1").getValue())); switch (format) { - case ATOM: - assertXpathExists("/d:TestFunctionReturnStringPatch", resource); - assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringPatch/text()", resource); - break; - case JSON: - assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_PATCH)); - assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); - break; - default: - throw new RuntimeException("Unknown Format Type: " + format); + case ATOM: + assertXpathExists("/d:TestFunctionReturnStringPatch", resource); + assertXpathEvaluatesTo(FunctionImportProducerMock.SOME_TEXT, "/d:TestFunctionReturnStringPatch/text()", + resource); + break; + case JSON: + assertTrue(format.toString(), resource.contains(MetadataUtil.TEST_FUNCTION_RETURN_STRING_PATCH)); + assertTrue(format.toString(), resource.contains(FunctionImportProducerMock.SOME_TEXT)); + break; + default: + throw new RuntimeException("Unknown Format Type: " + format); } } } @@ -942,12 +1012,15 @@ public void testMethodNotFound() throws XpathException, IOException, SAXExceptio public void testBatch() throws XpathException, IOException, SAXException { /* - * because of we don't have batch processing test we will to a sanity batch test here because of function call support - * for all http methods did affect batch implementation (s. EntietiesRequestResource). + * because of we don't have batch processing test we will to a sanity batch test + * here because of function call support + * for all http methods did affect batch implementation (s. + * EntietiesRequestResource). */ for (FormatType format : FunctionImportTest.formats) { - String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_POST + "/$batch" + "?" + this.formatQuery(format); + String uri = endpointUri + MetadataUtil.TEST_FUNCTION_RETURN_STRING_POST + "/$batch" + "?" + + this.formatQuery(format); Hashtable header = new Hashtable(); header.put("content-type", new MediaType("multipart", "mixed")); diff --git a/test-integration/src/test/java/org/odata4j/test/integration/issues/Issue16Test.java b/test-integration/src/test/java/org/odata4j/test/integration/issues/Issue16Test.java index 98f678d..3e63c93 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/issues/Issue16Test.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/issues/Issue16Test.java @@ -27,9 +27,11 @@ public Issue16Test(RuntimeFacadeType type) { protected void registerODataProducer() throws Exception { InMemoryProducer producer = new InMemoryProducer("Issue16") { @Override - public EntitiesResponse getNavProperty(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, QueryInfo queryInfo) { + public EntitiesResponse getNavProperty(ODataContext context, String entitySetName, OEntityKey entityKey, + String navProp, QueryInfo queryInfo) { actualNavProp[0] = navProp; - return Responses.entities(Enumerable. create().toList(), EdmEntitySet.newBuilder().setName("messageLog").build(), null, null); + return Responses.entities(Enumerable.create().toList(), + EdmEntitySet.newBuilder().setName("messageLog").build(), null, null); } }; @@ -38,7 +40,7 @@ public EntitiesResponse getNavProperty(ODataContext context, String entitySetNam @Test public void issue16() throws Exception { - sendRequest(BASE_URI + "Message(124L)/messageLog()").waitForDone(); + sendRequest(BASE_URI + "Message(124L)/messageLog()"); Assert.assertNotNull(actualNavProp[0]); Assert.assertEquals("messageLog", actualNavProp[0]); diff --git a/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomBaseTest.java b/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomBaseTest.java index 0cdca1e..0ca9d32 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomBaseTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomBaseTest.java @@ -1,6 +1,6 @@ package org.odata4j.test.integration.producer.custom; -import javax.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MediaType; import org.core4j.Func1; import org.junit.After; @@ -54,14 +54,14 @@ public void dumpResourceJSON(String path) { public void dumpResource(String path, FormatType ft) { String uri = endpointUri + path; switch (ft) { - case JSON: - this.rtFacade.accept(uri, MediaType.APPLICATION_JSON_TYPE); - break; - case ATOM: - this.rtFacade.accept(uri, MediaType.APPLICATION_ATOM_XML_TYPE); - break; - default: - break; + case JSON: + this.rtFacade.accept(uri, MediaType.APPLICATION_JSON_TYPE); + break; + case ATOM: + this.rtFacade.accept(uri, MediaType.APPLICATION_ATOM_XML_TYPE); + break; + default: + break; } System.out.println(this.rtFacade.getWebResource(uri)); } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomProducer.java b/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomProducer.java index 9ce6964..d058475 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomProducer.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomProducer.java @@ -12,7 +12,7 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.HttpHeaders; import org.odata4j.core.OCollection.Builder; import org.odata4j.core.OCollections; @@ -113,7 +113,8 @@ private List getDirectories(QueryInfo queryInfo) { } @Override - public CountResponse getNavPropertyCount(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, QueryInfo queryInfo) { + public CountResponse getNavPropertyCount(ODataContext context, String entitySetName, OEntityKey entityKey, + String navProp, QueryInfo queryInfo) { throw new NotImplementedException(); } @@ -209,30 +210,35 @@ private OEntity getType1(int i) { props.add(OProperties.string("Id", id)); Builder builder = OCollections.newBuilder(EdmSimpleType.STRING); - props.add(OProperties.collection("EmptyStrings", new EdmCollectionType(CollectionKind.Bag, EdmSimpleType.STRING), builder.build())); + props.add(OProperties.collection("EmptyStrings", new EdmCollectionType(CollectionKind.Bag, EdmSimpleType.STRING), + builder.build())); builder = OCollections.newBuilder(EdmSimpleType.STRING); for (int j = 0; j < 3; j++) { builder.add(OSimpleObjects.create(EdmSimpleType.STRING, "bagstring-" + j)); } - props.add(OProperties.collection("BagOStrings", new EdmCollectionType(CollectionKind.Bag, EdmSimpleType.STRING), builder.build())); + props.add(OProperties.collection("BagOStrings", new EdmCollectionType(CollectionKind.Bag, EdmSimpleType.STRING), + builder.build())); builder = OCollections.newBuilder(EdmSimpleType.STRING); for (int j = 0; j < 5; j++) { builder.add(OSimpleObjects.create(EdmSimpleType.STRING, "liststring-" + j)); } - props.add(OProperties.collection("ListOStrings", new EdmCollectionType(CollectionKind.List, EdmSimpleType.STRING), builder.build())); + props.add(OProperties.collection("ListOStrings", new EdmCollectionType(CollectionKind.List, EdmSimpleType.STRING), + builder.build())); builder = OCollections.newBuilder(EdmSimpleType.INT32); for (int j = 0; j < 5; j++) { builder.add(OSimpleObjects.create(EdmSimpleType.INT32, j)); } - props.add(OProperties.collection("BagOInts", new EdmCollectionType(CollectionKind.List, EdmSimpleType.INT32), builder.build())); + props.add(OProperties.collection("BagOInts", new EdmCollectionType(CollectionKind.List, EdmSimpleType.INT32), + builder.build())); EdmComplexType ct1 = this.getMetadata().findEdmComplexType("myns.ComplexType1"); OComplexObject.Builder cb = OComplexObjects.newBuilder(ct1); cb.add(OProperties.string("Prop1", "Val1")).add(OProperties.string("Prop2", "Val2")); - // hmmh, I swear I put a form of OProperties.complex that took an OComplexObject.... + // hmmh, I swear I put a form of OProperties.complex that took an + // OComplexObject.... props.add(OProperties.complex("Complex1", ct1, cb.build().getProperties())); builder = OCollections.newBuilder(ct1); @@ -271,7 +277,8 @@ public OEntity getMLE(OEntityKey entityKey, QueryInfo queryInfo) { } @Override - public EntityResponse getEntity(ODataContext context, String entitySetName, OEntityKey entityKey, EntityQueryInfo queryInfo) { + public EntityResponse getEntity(ODataContext context, String entitySetName, OEntityKey entityKey, + EntityQueryInfo queryInfo) { if (entitySetName.equals("Type1s")) { return Responses.entity(getType1(Integer.parseInt((String) entityKey.asSingleValue()))); } @@ -285,7 +292,8 @@ public EntityResponse getEntity(ODataContext context, String entitySetName, OEnt } @Override - public BaseResponse getNavProperty(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, QueryInfo queryInfo) { + public BaseResponse getNavProperty(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, + QueryInfo queryInfo) { throw new NotImplementedException(); } @@ -305,7 +313,8 @@ public EntityResponse createEntity(ODataContext context, String entitySetName, O } @Override - public EntityResponse createEntity(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, OEntity entity) { + public EntityResponse createEntity(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, + OEntity entity) { throw new UnsupportedOperationException("Not supported yet."); } @@ -335,17 +344,20 @@ public void createLink(ODataContext context, OEntityId sourceEntity, String targ } @Override - public void updateLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, OEntityKey oldTargetEntityKey, OEntityId newTargetEntity) { + public void updateLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, + OEntityKey oldTargetEntityKey, OEntityId newTargetEntity) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public void deleteLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, OEntityKey targetEntityKey) { + public void deleteLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, + OEntityKey targetEntityKey) { throw new UnsupportedOperationException("Not supported yet."); } @Override - public BaseResponse callFunction(ODataContext context, EdmFunctionImport name, Map params, QueryInfo queryInfo) { + public BaseResponse callFunction(ODataContext context, EdmFunctionImport name, Map params, + QueryInfo queryInfo) { throw new UnsupportedOperationException("Not supported yet."); } @@ -367,7 +379,7 @@ public void initResources() { protected OEntity getMLE(EdmEntitySet entitySet, String id, String content) { List> props = new ArrayList>(); props.add(OProperties.string("MLEProp1", "content length is " + content.length())); - return OEntities.create(entitySet, OEntityKey.create("Id", id), props, Collections. emptyList()); + return OEntities.create(entitySet, OEntityKey.create("Id", id), props, Collections.emptyList()); } private class MediaLinkExtensionFactory implements OMediaLinkExtensions { @@ -382,14 +394,15 @@ public OMediaLinkExtension create(ODataContext context) { private class MediaLinkExtension implements OMediaLinkExtension { @Override - public InputStream getInputStreamForMediaLinkEntry(ODataContext odataContext, OEntity mle, String etag, EntityQueryInfo query) { + public InputStream getInputStreamForMediaLinkEntry(ODataContext odataContext, OEntity mle, String etag, + EntityQueryInfo query) { if (null == odataContext) { throw new IllegalArgumentException("no odataContext?"); } String id = mle.getEntityKey().asSingleValue().toString(); - String content = mediaResources.get(id); // "here we have some content for the mle with id: " +; + String content = mediaResources.get(id); // "here we have some content for the mle with id: " +; if (content == null) { throw new NotFoundException(); } @@ -406,7 +419,8 @@ public String getMediaLinkContentType(ODataContext odataContext, OEntity mle) { } @Override - public OutputStream getOutputStreamForMediaLinkEntryCreate(ODataContext odataContext, OEntity mle, String etag, QueryInfo query) { + public OutputStream getOutputStreamForMediaLinkEntryCreate(ODataContext odataContext, OEntity mle, String etag, + QueryInfo query) { if (null == odataContext) { throw new IllegalArgumentException("no odataContext?"); } @@ -420,7 +434,8 @@ public OutputStream getOutputStreamForMediaLinkEntryCreate(ODataContext odataCon } @Override - public OutputStream getOutputStreamForMediaLinkEntryUpdate(ODataContext odataContext, OEntity mle, String etag, QueryInfo query) { + public OutputStream getOutputStreamForMediaLinkEntryUpdate(ODataContext odataContext, OEntity mle, String etag, + QueryInfo query) { if (null == odataContext) { throw new IllegalArgumentException("no odataContext?"); } @@ -433,7 +448,8 @@ public OutputStream getOutputStreamForMediaLinkEntryUpdate(ODataContext odataCon } @Override - public OEntity getMediaLinkEntryForUpdateOrDelete(ODataContext odataContext, EdmEntitySet entitySet, OEntityKey key, HttpHeaders httpHeaders) { + public OEntity getMediaLinkEntryForUpdateOrDelete(ODataContext odataContext, EdmEntitySet entitySet, OEntityKey key, + HttpHeaders httpHeaders) { if (null == odataContext) { throw new IllegalArgumentException("no odataContext?"); } @@ -496,7 +512,7 @@ public OEntity createMediaLinkEntry(ODataContext odataContext, EdmEntitySet enti // slug is the id List> props = new ArrayList>(); props.add(OProperties.string("MLEProp1", "prop1 initial value")); - return OEntities.create(entitySet, OEntityKey.create("Id", slugs.get(0)), props, Collections. emptyList()); + return OEntities.create(entitySet, OEntityKey.create("Id", slugs.get(0)), props, Collections.emptyList()); } @Override diff --git a/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomTest.java b/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomTest.java index b7bf234..f27dc6e 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/producer/custom/CustomTest.java @@ -12,8 +12,8 @@ import java.util.List; import java.util.Map; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response.Status; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response.Status; import org.junit.Test; import org.odata4j.consumer.ODataConsumer; @@ -254,7 +254,7 @@ private static interface ValueGenerator { @SuppressWarnings("unchecked") private void checkCollection(OProperty prop, EdmType itemType, ValueGenerator vg) { - //OProperty prop = e.getProperty("BagOStrings"); + // OProperty prop = e.getProperty("BagOStrings"); assertTrue(prop != null); assertTrue(prop.getType() instanceof EdmCollectionType); EdmCollectionType ct = (EdmCollectionType) prop.getType(); @@ -278,18 +278,21 @@ public void testMLE() throws InterruptedException { @Test public void testCreateMLE() throws InterruptedException { /** - * There appears to be a strange race condition or something in the test environment: + * There appears to be a strange race condition or something in the test + * environment: * if the first request to the server has a payload, the server can - * timeout waiting for data from the client. Not sure why or if it is a client - * or server issue. Workaround: issue a GET first to prime things. + * timeout waiting for data from the client. Not sure why or if it is a client + * or server issue. Workaround: issue a GET first to prime things. */ - String contentBefore = rtFacade.getWebResource(endpointUri + "MLEs('ANewMLE')/$value" + "?$format=json").getEntity(); + String contentBefore = rtFacade.getWebResource(endpointUri + "MLEs('ANewMLE')/$value" + "?$format=json") + .getEntity(); Map headers = new HashMap(); headers.put("Slug", "ANewMLE"); // the Id String content = "This MLE was created by the test testCreateMLE()"; - int status = rtFacade.postWebResource(endpointUri + "MLEs", new ByteArrayInputStream(content.getBytes()), MediaType.APPLICATION_OCTET_STREAM_TYPE, headers).getStatusCode(); + int status = rtFacade.postWebResource(endpointUri + "MLEs", new ByteArrayInputStream(content.getBytes()), + MediaType.APPLICATION_OCTET_STREAM_TYPE, headers).getStatusCode(); assertEquals(Status.CREATED.getStatusCode(), status); String content2 = rtFacade.getWebResource(endpointUri + "MLEs('ANewMLE')/$value" + "?$format=json").getEntity(); @@ -299,15 +302,17 @@ public void testCreateMLE() throws InterruptedException { @Test public void testUpdateMLE() { /** - * There appears to be a strange race condition or something in the test environment: + * There appears to be a strange race condition or something in the test + * environment: * if the first request to the server has a payload, the server can - * timeout waiting for data from the client. Not sure why or if it is a client - * or server issue. Workaround: issue a GET first to prime things. + * timeout waiting for data from the client. Not sure why or if it is a client + * or server issue. Workaround: issue a GET first to prime things. */ String contentBefore = rtFacade.getWebResource(endpointUri + "MLEs('foobar')/$value" + "?$format=json").getEntity(); String content = "This MLE was updated by the test testUpdateMLE()"; - int status = rtFacade.putWebResource(endpointUri + "MLEs('foobar')", new ByteArrayInputStream(content.getBytes()), MediaType.TEXT_PLAIN_TYPE, null).getStatusCode(); + int status = rtFacade.putWebResource(endpointUri + "MLEs('foobar')", new ByteArrayInputStream(content.getBytes()), + MediaType.TEXT_PLAIN_TYPE, null).getStatusCode(); assertEquals(Status.OK.getStatusCode(), status); String content2 = rtFacade.getWebResource(endpointUri + "MLEs('foobar')/$value" + "?$format=json").getEntity(); diff --git a/test-integration/src/test/java/org/odata4j/test/integration/roundtrip/AddressBookJettyHttpClientTest.java b/test-integration/src/test/java/org/odata4j/test/integration/roundtrip/AddressBookJettyHttpClientTest.java index c13531a..bb61938 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/roundtrip/AddressBookJettyHttpClientTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/roundtrip/AddressBookJettyHttpClientTest.java @@ -6,7 +6,7 @@ import java.util.List; -import org.eclipse.jetty.client.ContentExchange; +import org.eclipse.jetty.client.api.ContentResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -46,23 +46,23 @@ protected void registerODataProducer() throws Exception { @Test public void stringProperty() throws Exception { - ContentExchange exchange = sendRequest("Persons(1)/Name", format); + ContentResponse response = sendRequest("Persons(1)/Name", format); if (format.equals(JSON)) - assertThat(exchange.getResponseContent(), containsString("\"Susan Summer\"")); + assertThat(response.getContentAsString(), containsString("\"Susan Summer\"")); else - assertThat(exchange.getResponseContent(), containsString(">Susan Summer<")); + assertThat(response.getContentAsString(), containsString(">Susan Summer<")); } @Test public void dateTimeProperty() throws Exception { - ContentExchange exchange = sendRequest("Persons(2)/BirthDay", format); + ContentResponse response = sendRequest("Persons(2)/BirthDay", format); if (format.equals(JSON)) - assertThat(exchange.getResponseContent(), containsString("\"\\/Date(-62121600000)\\/\"")); + assertThat(response.getContentAsString(), containsString("\"\\/Date(-62121600000)\\/\"")); else - assertThat(exchange.getResponseContent(), containsString(">1968-01-13T00:00<")); + assertThat(response.getContentAsString(), containsString(">1968-01-13T00:00<")); } - private ContentExchange sendRequest(String requestUri, FormatType format) throws Exception { + private ContentResponse sendRequest(String requestUri, FormatType format) throws Exception { return sendRequest(BASE_URI + requestUri + (!requestUri.contains("?") ? "?" : "") + "$format=" + format); } } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/server/ContextTest.java b/test-integration/src/test/java/org/odata4j/test/integration/server/ContextTest.java index cde58fb..3eced5b 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/server/ContextTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/server/ContextTest.java @@ -8,7 +8,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -17,9 +16,12 @@ import java.util.Map; import java.util.Map.Entry; -import javax.ws.rs.core.SecurityContext; +import jakarta.ws.rs.core.SecurityContext; -import org.eclipse.jetty.client.ContentExchange; +import org.eclipse.jetty.client.api.ContentResponse; +import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.client.util.StringContentProvider; +import org.eclipse.jetty.http.HttpMethod; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; @@ -96,7 +98,7 @@ public void initTest() { @Test public void testGetEntities() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories", myHeaders); verify(producer).getEntities(context.capture(), eq("Directories"), any(QueryInfo.class)); @@ -106,7 +108,7 @@ public void testGetEntities() throws IOException, Exception { @Test public void testGetEntitiesCount() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories/$count", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories/$count", myHeaders); verify(producer).getEntitiesCount(context.capture(), eq("Directories"), any(QueryInfo.class)); @@ -116,7 +118,7 @@ public void testGetEntitiesCount() throws IOException, Exception { @Test public void testGetEntity() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')", myHeaders); verify(producer).getEntity(context.capture(), eq("Directories"), any(OEntityKey.class), any(EntityQueryInfo.class)); @@ -126,9 +128,10 @@ public void testGetEntity() throws IOException, Exception { @Test public void testGetNavProperty() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/Files", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/Files", myHeaders); - verify(producer).getNavProperty(context.capture(), eq("Directories"), any(OEntityKey.class), eq("Files"), any(QueryInfo.class)); + verify(producer).getNavProperty(context.capture(), eq("Directories"), any(OEntityKey.class), eq("Files"), + any(QueryInfo.class)); assertContext(); } @@ -136,9 +139,10 @@ public void testGetNavProperty() throws IOException, Exception { @Test public void testGetNavPropertyCount() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/Files/$count", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/Files/$count", myHeaders); - verify(producer).getNavPropertyCount(context.capture(), eq("Directories"), any(OEntityKey.class), eq("Files"), any(QueryInfo.class)); + verify(producer).getNavPropertyCount(context.capture(), eq("Directories"), any(OEntityKey.class), eq("Files"), + any(QueryInfo.class)); assertContext(); } @@ -146,7 +150,8 @@ public void testGetNavPropertyCount() throws IOException, Exception { @Test public void testCreateEntity() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories", myHeaders, "POST", "{ \"Name\" : \"NewDir\" }"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories", myHeaders, "POST", + "{ \"Name\" : \"NewDir\" }"); verify(producer).createEntity(context.capture(), eq("Directories"), any(OEntity.class)); @@ -156,9 +161,11 @@ public void testCreateEntity() throws IOException, Exception { @Test public void testCreateRelatedEntity() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')/Items", myHeaders, "POST", "{ \"Name\" : \"NewFile\" }"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')/Items", myHeaders, "POST", + "{ \"Name\" : \"NewFile\" }"); - verify(producer).createEntity(context.capture(), eq("Directories"), any(OEntityKey.class), eq("Items"), any(OEntity.class)); + verify(producer).createEntity(context.capture(), eq("Directories"), any(OEntityKey.class), eq("Items"), + any(OEntity.class)); assertContext(); } @@ -166,7 +173,7 @@ public void testCreateRelatedEntity() throws IOException, Exception { @Test public void testDeleteEntity() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')", myHeaders, "DELETE", ""); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')", myHeaders, "DELETE", ""); verify(producer).deleteEntity(context.capture(), eq("Directories"), any(OEntityKey.class)); @@ -178,7 +185,8 @@ public void testMergeEntity() throws IOException, Exception { Map> headers = getHeaders(); headers.put(Headers.X_HTTP_METHOD, Collections.singletonList("MERGE")); - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')", headers, "POST", "{ \"DirProp1\" : \"prop1value\" }"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')", headers, "POST", + "{ \"DirProp1\" : \"prop1value\" }"); verify(producer).mergeEntity(context.capture(), eq("Directories"), any(OEntity.class)); @@ -189,7 +197,8 @@ public void testMergeEntity() throws IOException, Exception { public void testUpdateEntity() throws IOException, Exception { Map> headers = getHeaders(); - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')", headers, "PUT", "{ \"DirProp1\" : \"prop1value\" }"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('MyDir')", headers, "PUT", + "{ \"DirProp1\" : \"prop1value\" }"); verify(producer).updateEntity(context.capture(), eq("Directories"), any(OEntity.class)); @@ -199,7 +208,7 @@ public void testUpdateEntity() throws IOException, Exception { @Test public void testGetLinks() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders); verify(producer).getLinks(context.capture(), any(OEntityId.class), eq("Files")); @@ -209,7 +218,8 @@ public void testGetLinks() throws IOException, Exception { @Test public void testCreateLink() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders, "POST", "{\"uri\": \"http://host/service.svc/Files('myfile')\"}"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders, "POST", + "{\"uri\": \"http://host/service.svc/Files('myfile')\"}"); verify(producer).createLink(context.capture(), any(OEntityId.class), eq("Files"), any(OEntityId.class)); @@ -219,9 +229,11 @@ public void testCreateLink() throws IOException, Exception { @Test public void testUpdateLink() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders, "PUT", "{\"uri\": \"http://host/service.svc/Files('myfile2')\"}"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders, "PUT", + "{\"uri\": \"http://host/service.svc/Files('myfile2')\"}"); - verify(producer).updateLink(context.capture(), any(OEntityId.class), eq("Files"), any(OEntityKey.class), any(OEntityId.class)); + verify(producer).updateLink(context.capture(), any(OEntityId.class), eq("Files"), any(OEntityKey.class), + any(OEntityId.class)); assertContext(); } @@ -229,7 +241,8 @@ public void testUpdateLink() throws IOException, Exception { @Test public void testDeleteLink() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders, "DELETE", "{\"uri\": \"http://host/service.svc/Files('myfile2')\"}"); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "Directories('Dir-0')/$links/Files", myHeaders, + "DELETE", "{\"uri\": \"http://host/service.svc/Files('myfile2')\"}"); verify(producer).deleteLink(context.capture(), any(OEntityId.class), eq("Files"), any(OEntityKey.class)); @@ -239,9 +252,10 @@ public void testDeleteLink() throws IOException, Exception { @Test public void testCallFunction() throws IOException, Exception { - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "f?p='foo'", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "f?p='foo'", myHeaders); - verify(producer).callFunction(context.capture(), any(EdmFunctionImport.class), any(Map.class), any(QueryInfo.class)); + verify(producer).callFunction(context.capture(), any(EdmFunctionImport.class), any(Map.class), + any(QueryInfo.class)); assertContext(); } @@ -251,7 +265,7 @@ public void testMLE() throws IOException, Exception { producer.extensionFactory = mock(OMediaLinkExtensions.class); - ContentExchange exchange = sendRequestWithHeaders(BASE_URI + "MLEs('foobar')/$value", myHeaders); + ContentResponse response = sendRequestWithHeaders(BASE_URI + "MLEs('foobar')/$value", myHeaders); verify(producer).findExtension(OMediaLinkExtensions.class); verify(producer.extensionFactory).create(context.capture()); @@ -264,7 +278,8 @@ private void assertContext() { private void assertContext(Map> headers) { - // first: did all of the headers we sent make it into the producer via ODataContext? + // first: did all of the headers we sent make it into the producer via + // ODataContext? assertHeaders(headers); // next: did the SecurityContext make it into the producer via ODataContext? @@ -293,29 +308,32 @@ private void assertHeaders(Map> headers) { } } - private ContentExchange sendRequestWithHeaders(String url, Map> headers) throws IOException, InterruptedException { + private ContentResponse sendRequestWithHeaders(String url, Map> headers) + throws Exception { return sendRequestWithHeaders(url, headers, null, null); } - private ContentExchange sendRequestWithHeaders(String url, Map> headers, String method, String payload) throws IOException, InterruptedException { - ContentExchange exchange = new ContentExchange(true); - exchange.setURL(url); - if (null != method) { - exchange.setMethod(method); + private ContentResponse sendRequestWithHeaders(String url, Map> headers, String method, + String payload) throws Exception { + + Request request = client.newRequest(url); + + if (method != null) { + request.method(HttpMethod.fromString(method)); } - if (null != payload) { - exchange.setRequestContentSource(new ByteArrayInputStream(payload.getBytes())); + + if (payload != null) { + request.content(new StringContentProvider(payload), "application/json"); } for (Entry> e : headers.entrySet()) { for (String val : e.getValue()) { - exchange.addRequestHeader(e.getKey(), val); + request.header(e.getKey(), val); } } - client.send(exchange); - exchange.waitForDone(); - return exchange; + ContentResponse response = request.send(); + return response; } } diff --git a/test-integration/src/test/java/org/odata4j/test/integration/server/ErrorTest.java b/test-integration/src/test/java/org/odata4j/test/integration/server/ErrorTest.java index 6d21038..e69de29 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/server/ErrorTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/server/ErrorTest.java @@ -1,106 +0,0 @@ -package org.odata4j.test.integration.server; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.util.regex.Pattern; - -import javax.ws.rs.core.MediaType; - -import org.eclipse.jetty.client.ContentExchange; -import org.eclipse.jetty.client.HttpExchange; -import org.eclipse.jetty.http.HttpHeaders; -import org.eclipse.jetty.http.HttpStatus; -import org.junit.Test; -import org.odata4j.producer.ErrorResponseExtension; -import org.odata4j.producer.ErrorResponseExtensions; -import org.odata4j.producer.inmemory.InMemoryProducer; -import org.odata4j.producer.resources.DefaultODataProducerProvider; -import org.odata4j.test.integration.AbstractJettyHttpClientTest; -import org.odata4j.test.integration.TestInMemoryProducers; - -public class ErrorTest extends AbstractJettyHttpClientTest { - - private static final String FEED_URL = BASE_URI + TestInMemoryProducers.SIMPLE_ENTITY_SET_NAME; - - private InMemoryProducer producerSpy; - - public ErrorTest(RuntimeFacadeType type) { - super(type); - } - - @Override - protected void registerODataProducer() throws Exception { - producerSpy = spy(TestInMemoryProducers.simple()); - DefaultODataProducerProvider.setInstance(producerSpy); - } - - private void simulateErrorResponseExtension() { - when(producerSpy.findExtension(ErrorResponseExtension.class)).thenReturn(ErrorResponseExtensions.returnInnerErrors()); - } - - @Test - public void notFoundXml() throws Exception { - ContentExchange exchange = sendRequest(FEED_URL + "('Z')"); - exchange.waitForDone(); - assertThat(exchange.getStatus(), is(HttpExchange.STATUS_COMPLETED)); - assertThat(exchange.getResponseStatus(), is(HttpStatus.NOT_FOUND_404)); - assertThat(exchange.getResponseFields().getStringField(HttpHeaders.CONTENT_TYPE), containsString(MediaType.APPLICATION_XML)); - assertThat(exchange.getResponseContent().length(), greaterThan(0)); - assertRegexMatches(exchange.getResponseContent(), ".*NotFoundException.*"); - assertRegexNotMatches(exchange.getResponseContent(), ".*.+.*"); - } - - @Test - public void notFoundJson() throws Exception { - ContentExchange exchange = sendRequest(FEED_URL + "('Z')?$format=json"); - exchange.waitForDone(); - assertThat(exchange.getStatus(), is(HttpExchange.STATUS_COMPLETED)); - assertThat(exchange.getResponseStatus(), is(HttpStatus.NOT_FOUND_404)); - assertThat(exchange.getResponseFields().getStringField(HttpHeaders.CONTENT_TYPE), containsString(MediaType.APPLICATION_JSON)); - assertThat(exchange.getResponseContent().length(), greaterThan(0)); - assertRegexMatches(exchange.getResponseContent(), ".*\"code\"\\s*:\\s*\"NotFoundException\".*"); - assertRegexNotMatches(exchange.getResponseContent(), ".*\"innererror\"\\s*:\\s*\".+\".*"); - } - - @Test - public void badRequestXmlWithInnerError() throws Exception { - simulateErrorResponseExtension(); - ContentExchange exchange = sendRequest(FEED_URL + "(1.2)"); - exchange.waitForDone(); - assertThat(exchange.getStatus(), is(HttpExchange.STATUS_COMPLETED)); - assertThat(exchange.getResponseStatus(), is(HttpStatus.BAD_REQUEST_400)); - assertThat(exchange.getResponseFields().getStringField(HttpHeaders.CONTENT_TYPE), containsString(MediaType.APPLICATION_XML)); - assertThat(exchange.getResponseContent().length(), greaterThan(0)); - assertRegexMatches(exchange.getResponseContent(), ".*BadRequestException.*.+.*"); - } - - @Test - public void badRequestJsonWithInnerError() throws Exception { - simulateErrorResponseExtension(); - ContentExchange exchange = sendRequest(FEED_URL + "(1.2)?$format=json"); - exchange.waitForDone(); - assertThat(exchange.getStatus(), is(HttpExchange.STATUS_COMPLETED)); - assertThat(exchange.getResponseStatus(), is(HttpStatus.BAD_REQUEST_400)); - assertThat(exchange.getResponseFields().getStringField(HttpHeaders.CONTENT_TYPE), containsString(MediaType.APPLICATION_JSON)); - assertThat(exchange.getResponseContent().length(), greaterThan(0)); - assertRegexMatches(exchange.getResponseContent(), ".*\"code\"\\s*:\\s*\"BadRequestException\".*\"innererror\"\\s*:\\s*\".+\".*"); - } - - private void assertRegexMatches(String source, String target) throws Exception { - assertRegexMatches(source, target, true); - } - - private void assertRegexNotMatches(String source, String target) throws Exception { - assertRegexMatches(source, target, false); - } - - private void assertRegexMatches(String source, String target, boolean matches) throws Exception { - assertEquals(matches, Pattern.compile(target, Pattern.DOTALL).matcher(source).matches()); - } -} diff --git a/test-integration/src/test/java/org/odata4j/test/integration/server/RequestFilteringTest.java b/test-integration/src/test/java/org/odata4j/test/integration/server/RequestFilteringTest.java index 2d3a2eb..d884b01 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/server/RequestFilteringTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/server/RequestFilteringTest.java @@ -7,22 +7,22 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; -import org.eclipse.jetty.client.ContentExchange; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.DefaultHandler; +import org.glassfish.jersey.server.ContainerRequest; import org.junit.Test; import org.odata4j.examples.cxf.producer.server.ODataCxfServer; import org.odata4j.examples.jersey.producer.server.ODataJerseyServer; import org.odata4j.producer.resources.DefaultODataProducerProvider; import org.odata4j.test.integration.AbstractJettyHttpClientTest; import org.odata4j.test.integration.TestInMemoryProducers; - -import com.sun.jersey.spi.container.ContainerRequest; -import com.sun.jersey.spi.container.ContainerRequestFilter; +import org.eclipse.jetty.client.api.ContentResponse; public class RequestFilteringTest extends AbstractJettyHttpClientTest { @@ -43,9 +43,8 @@ public static class JerseyRequestFilterStub implements ContainerRequestFilter { static boolean isCalled = false; @Override - public ContainerRequest filter(ContainerRequest request) { + public void filter(ContainerRequestContext request) { isCalled = true; - return request; } } @@ -63,15 +62,16 @@ protected void registerODataProducer() throws Exception { @Test public void filterIsCalled() throws Exception { - ContentExchange exchange = sendRequest(BASE_URI); - exchange.waitForDone(); + ContentResponse response = sendRequest(BASE_URI); + // exchange.waitForDone(); verifyFilterIsCalled(); } private void verifyFilterIsCalled() throws Exception { if (server instanceof ODataCxfServer) - verify(jettyRequestHandler, atLeastOnce()).handle(anyString(), any(Request.class), any(HttpServletRequest.class), any(HttpServletResponse.class)); + verify(jettyRequestHandler, atLeastOnce()).handle(anyString(), any(Request.class), any(HttpServletRequest.class), + any(HttpServletResponse.class)); else if (server instanceof ODataJerseyServer) assertTrue("Request filter has not been called", JerseyRequestFilterStub.isCalled); } -} +} \ No newline at end of file diff --git a/test-integration/src/test/java/org/odata4j/test/integration/server/SmokeTest.java b/test-integration/src/test/java/org/odata4j/test/integration/server/SmokeTest.java index 5eed442..8767705 100644 --- a/test-integration/src/test/java/org/odata4j/test/integration/server/SmokeTest.java +++ b/test-integration/src/test/java/org/odata4j/test/integration/server/SmokeTest.java @@ -4,8 +4,7 @@ import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; -import org.eclipse.jetty.client.ContentExchange; -import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpStatus; import org.junit.Test; import org.odata4j.producer.resources.DefaultODataProducerProvider; @@ -14,9 +13,6 @@ public class SmokeTest extends AbstractJettyHttpClientTest { - private static final String META_DATA_URL = BASE_URI + "$metadata"; - private static final String FEED_URL = BASE_URI + TestInMemoryProducers.SIMPLE_ENTITY_SET_NAME; - public SmokeTest(RuntimeFacadeType type) { super(type); } @@ -28,28 +24,24 @@ protected void registerODataProducer() throws Exception { @Test public void serviceUrlReturnsOkStatus() throws Exception { - ContentExchange exchange = sendRequest(BASE_URI); - exchange.waitForDone(); - verifyOkStatusIsReturned(exchange); + ContentResponse response = sendRequest(BASE_URI); + verifyOkStatusIsReturned(response); } @Test public void metaDataUrlReturnsOkStatus() throws Exception { - ContentExchange exchange = sendRequest(META_DATA_URL); - exchange.waitForDone(); - verifyOkStatusIsReturned(exchange); + ContentResponse response = sendRequest(BASE_URI + "$metadata"); + verifyOkStatusIsReturned(response); } @Test public void feedUrlReturnsOkStatus() throws Exception { - ContentExchange exchange = sendRequest(FEED_URL); - exchange.waitForDone(); - verifyOkStatusIsReturned(exchange); + ContentResponse response = sendRequest(BASE_URI + TestInMemoryProducers.SIMPLE_ENTITY_SET_NAME); + verifyOkStatusIsReturned(response); } - private void verifyOkStatusIsReturned(ContentExchange exchange) throws Exception { - assertThat(exchange.getStatus(), is(HttpExchange.STATUS_COMPLETED)); - assertThat(exchange.getResponseStatus(), is(HttpStatus.OK_200)); - assertThat(exchange.getResponseContent().length(), greaterThan(0)); + private void verifyOkStatusIsReturned(ContentResponse response) throws Exception { + assertThat(response.getStatus(), is(HttpStatus.OK_200)); + assertThat(response.getContentAsString().length(), greaterThan(0)); } } From c131b49096542746d54e7fd2fa3700d448aff61f Mon Sep 17 00:00:00 2001 From: thiagotognoli Date: Fri, 1 Aug 2025 23:07:43 -0300 Subject: [PATCH 2/3] remove trash --- .../consumer/ODataClientBatchResponse.java | 31 ---- .../jersey/consumer/ODataJerseyClient.java | 135 ------------------ 2 files changed, 166 deletions(-) delete mode 100644 odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java diff --git a/odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java b/odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java deleted file mode 100644 index 404c0a1..0000000 --- a/odata-core/src/main/java/org/odata4j/consumer/ODataClientBatchResponse.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.odata4j.consumer; - -/** - * This interface define the result returned from batch request. - * The result depends on request type. - * All the request will return a staus code, but not all requests will return - * entity. - * - * @author Kevin Chen - * - */ -public interface ODataClientBatchResponse extends ODataClientResponse { - /** - * Return the status code of this individual request. - * - * @return the status code. - */ - public int getStatus(); - - /** - * Return the content. The content is based on the request. - * getEntities request ---> Enumerable - * getEntity request ------> T - * createEntity request ----> T - * update/delete request -----> null - * T is the entity type request. - * - * @return the entities. - */ - public Object getEntity(); -} diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java index bea1b8e..5120ddb 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/ODataJerseyClient.java @@ -103,141 +103,6 @@ public String requestBody(FormatType formatType, ODataClientRequest request) thr return entity; } - // /** - // * This is consumer side to create a batch request, and then handle the - // * response. - // * - // * @param batchRequest - // * the batchRequest is a POST with end point $batch, the - // * content-type should be multipart/mixed. - // * @param childRequests - // * this is a list of the operation that will be part of the - // * batch request. it can also contain - // * change set. - // * - // */ - // public List batchRequest(FormatType reqType1, - // ODataClientRequest batchRequest, - // List childRequests) { - - // List result = null; - // if (behaviors != null) { - // for (OClientBehavior behavior : behaviors) - // batchRequest = behavior.transform(batchRequest); - // } - - // WebTarget webResource = JerseyClientUtil.resource(client, - // batchRequest.getUrl(), behaviors); - // Invocation.Builder b = webResource.request(); - // String boundary = null; - // String cType = null; - - // FormatType formatType = getFormatType(); - // // set headers - // b = b.accept(formatType.getAcceptableMediaTypes()); - - // for (String header : batchRequest.getHeaders().keySet()) { - // // parse content type to get the boundary string - // if (header.equals(ODataConstants.Headers.CONTENT_TYPE)) { - // cType = batchRequest.getHeaders().get(header); - // boundary = cType.substring(cType.indexOf('=') + 1); - // } - // b.header(header, batchRequest.getHeaders().get(header)); - // } - - // if (ODataConsumer.dump.requestHeaders()) - // dumpHeaders(batchRequest, webResource, b); - - // if (boundary == null) { - // throw new BadRequestException("batchRequest's content type should contain - // boundary"); - // } - // // now create the pay load for the batch request - // StringBuilder sb = new StringBuilder(); - // for (Object req : childRequests) { - // // new way to add the request - // sb.append("\n--").append(boundary).append("\n"); - // sb.append(((OBatchSupport) req).formatRequest(this.getFormatType())); - // } - - // // ending the batch multi part - // if (childRequests.size() > 0) { - // sb.append("\n--").append(boundary).append("--\n"); - // } - - // String entity = sb.toString(); - - // if (ODataConsumer.dump.requestBody()) { - // dump(entity); - // } - - // // execute request - // ClientResponse response = b.method(batchRequest.getMethod(), - // Entity.entity(entity, cType), ClientResponse.class); - // Integer status = response.getStatus(); - // String responseContentType = - // response.getHeaders().getFirst(ODataConstants.Headers.CONTENT_TYPE); - // MediaType mType = getMediaType(responseContentType); - // // check the response if it is multi part, if not, an error occured, throw - // // exception - // if (!mType.isCompatible(MULTIPART_BASE_TYPE)) { - // String errMsg = response.readEntity(String.class); - // OError error = OErrors.error(status.toString(), errMsg, null); - // throw new ServerErrorException.Factory().createException(error); - // } - // result = parseResponse(response, childRequests); - - // return result; - // } - - // private List parseResponse(ClientResponse response, - // List childRequests) { - - // ODataVersion version = - // InternalUtil.getDataServiceVersion(response.getHeaders() - // .getFirst(ODataConstants.Headers.DATA_SERVICE_VERSION)); - - // MultiPart mp = response.readEntity(MultiPart.class); // input stream can only - // be consumed once - - // // this is the list will hold individual request result. - // List batchResultList = new - // ArrayList(childRequests.size()); - - // if (ODataConsumer.dump.responseHeaders()) { - // dumpHeaders(response); - // } - - // int i = 0; - // for (BodyPart bp : mp.getBodyParts()) { - // ODataClientBatchResponse ocbr = null; - // MediaType cType = bp.getMediaType(); - // if (cType.isCompatible(new MediaType("multipart", "mixed"))) { - // MultiPart cmp = bp.getEntityAs(MultiPart.class); - // OChangeSetRequest csr = (OChangeSetRequest) childRequests.get(i); - - // List payloadList = new ArrayList(); - - // for (BodyPart cbp : cmp.getBodyParts()) { - // String content = cbp.getEntityAs(String.class); - // payloadList.add(content); - // } - // ocbr = ConsumerBatchRequestHelper.parseChangeSetOperationResponse(version, - // payloadList, csr, getFormatType()); - // } else { - // String content = bp.getEntityAs(String.class); - // OBatchSupport so = (OBatchSupport) childRequests.get(i); - // ocbr = ConsumerBatchRequestHelper.parseSingleOperationResponse(version, - // content, so, getFormatType()); - // } - - // batchResultList.add(ocbr); - // i++; - // } - - // return batchResultList; - // } - @SuppressWarnings("unchecked") protected ODataClientResponse doRequest(FormatType reqType, ODataClientRequest request, StatusType... expectedResponseStatus) throws ODataProducerException { From 7d61f3649258fd1a1661b6cd6836ec30dd0b0113 Mon Sep 17 00:00:00 2001 From: thiagotognoli Date: Fri, 1 Aug 2025 23:17:25 -0300 Subject: [PATCH 3/3] trash --- .../examples/jersey/consumer/DefaultJerseyClientFactory.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java index e6a7edf..a7e17a7 100644 --- a/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java +++ b/test-integration/src/main/java/org/odata4j/examples/jersey/consumer/DefaultJerseyClientFactory.java @@ -1,8 +1,5 @@ package org.odata4j.examples.jersey.consumer; -import org.glassfish.jersey.client.JerseyClient; -import org.glassfish.jersey.client.JerseyClientBuilder; - import jakarta.ws.rs.client.Client; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.JerseyClient;