diff --git a/CHANGELOG.md b/CHANGELOG.md index 90258a9c..420ed083 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ ## Release Notes +`1.3.0` + +- Added Jackson 3 support to `SpringJson` via `Jackson3SpringJson` for `JacksonJsonHttpMessageConverter`. +- Upgraded `httpclient5` to `5.6.5`. +- Upgraded OkHttp to `4.12.1`. +- Upgraded Jackson 2 to `2.21.7`. +- Upgraded Jackson 3 to `3.1.7`. +- Upgraded Spring Boot to `4.1.2` for `apiphany-spring`. +- Upgraded Spring to `7.0.10` for `apiphany-spring`. +- Upgraded Micrometer to `1.17.2`. +- Upgraded SLF4J to `2.0.20`. +- Upgraded `spring-security-oauth2-client` to `7.1.2`. +- Upgraded `nimbus-jose-jwt` to `10.10`. +- Upgraded `mockito-core` to `5.24.0`. +- Upgraded `logback-core` to `1.5.38`. +- Upgraded `testcontainers-keycloak` to `4.4.0`. +- Upgraded `pitest-maven` to `1.30.1`. +- Upgraded `maven-compiler-plugin` to `3.16.0`. +- Upgraded `maven-surefire-plugin` to `3.6.1`. +- Upgraded `maven-failsafe-plugin` to `3.6.1`. +- Upgraded `jacoco-maven-plugin` to `0.8.16`. +- Upgraded `spotless-maven-plugin` to `3.10.4`. +- Upgraded `maven-deploy-plugin` to `3.2.0`. +- Upgraded `exec-maven-plugin ` to `3.6.4`. + +--- + `1.2.23` - Added `ApiResponse.isFailed()` to report whether the response status is an error, mirroring `isSuccessful()`. diff --git a/README.md b/README.md index 05123e43..20b47faa 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Support is being developed for other HTTP clients like Netty, Jersey, etc. If yo ### Releases -Current release `1.2.23` +Current release `1.3.0` ### Getting Started @@ -62,7 +62,7 @@ Maven: add this dependency to your `pom.xml` io.github.raduking apiphany - 1.2.23 + 1.3.0 ``` diff --git a/apiphany-core/pom.xml b/apiphany-core/pom.xml index 0a49bb74..10f3d7d6 100644 --- a/apiphany-core/pom.xml +++ b/apiphany-core/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 apiphany diff --git a/apiphany-httpclient5/pom.xml b/apiphany-httpclient5/pom.xml index ec5a7a94..a0ac0eae 100644 --- a/apiphany-httpclient5/pom.xml +++ b/apiphany-httpclient5/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 apiphany-httpclient5 diff --git a/apiphany-httpclient5/src/main/java/org/apiphany/http/ApacheHC5Library.java b/apiphany-httpclient5/src/main/java/org/apiphany/http/ApacheHC5Library.java index e6d71cb2..14651ce3 100644 --- a/apiphany-httpclient5/src/main/java/org/apiphany/http/ApacheHC5Library.java +++ b/apiphany-httpclient5/src/main/java/org/apiphany/http/ApacheHC5Library.java @@ -31,7 +31,7 @@ public class ApacheHC5Library { *

* A newer runtime version is outside the tested range and is rejected by {@link #verifyVersion()}. */ - private static final LibraryVersion MAXIMUM_VERSION = LibraryVersion.of(CLIENT_NAME, 5, 6, 4); + private static final LibraryVersion MAXIMUM_VERSION = LibraryVersion.of(CLIENT_NAME, 5, 6, 5); /** * The Apache HttpClient 5 CloseableHttpClient class name. diff --git a/apiphany-httpclient5/src/test/java/org/apiphany/http/ApacheHC5LibraryTest.java b/apiphany-httpclient5/src/test/java/org/apiphany/http/ApacheHC5LibraryTest.java index 05e9fdcd..425b2791 100644 --- a/apiphany-httpclient5/src/test/java/org/apiphany/http/ApacheHC5LibraryTest.java +++ b/apiphany-httpclient5/src/test/java/org/apiphany/http/ApacheHC5LibraryTest.java @@ -19,6 +19,9 @@ */ class ApacheHC5LibraryTest { + public static final String MIN_SUPPORTED_VERSION = "5.5.0"; + public static final String MAX_SUPPORTED_VERSION = "5.6.5"; + @Nested class IsPresentTests { @@ -84,7 +87,7 @@ class MinimumVersionTests { @Test void shouldReturnMinimumRequiredVersion() { - assertThat(ApacheHC5Library.minimumVersion().value(), equalTo("5.5.0")); + assertThat(ApacheHC5Library.minimumVersion().value(), equalTo(MIN_SUPPORTED_VERSION)); } @Test @@ -98,7 +101,7 @@ class MaximumVersionTests { @Test void shouldReturnMaximumSupportedVersion() { - assertThat(ApacheHC5Library.maximumVersion().value(), equalTo("5.6.4")); + assertThat(ApacheHC5Library.maximumVersion().value(), equalTo(MAX_SUPPORTED_VERSION)); } } diff --git a/apiphany-integration-tests/pom.xml b/apiphany-integration-tests/pom.xml index c26835a0..ef69df6b 100644 --- a/apiphany-integration-tests/pom.xml +++ b/apiphany-integration-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 apiphany-integration-tests diff --git a/apiphany-integration-tests/src/test/java/org/apiphany/tests/security/ssl/client/SSLClientIT.java b/apiphany-integration-tests/src/test/java/org/apiphany/tests/security/ssl/client/SSLClientIT.java index 56ce4c7b..dc82ed92 100644 --- a/apiphany-integration-tests/src/test/java/org/apiphany/tests/security/ssl/client/SSLClientIT.java +++ b/apiphany-integration-tests/src/test/java/org/apiphany/tests/security/ssl/client/SSLClientIT.java @@ -72,9 +72,10 @@ void shouldNotGetNameIfSSLIsNotInitialized() throws Exception { assertNotNull(exception); assertThat(exception.getClass(), equalTo(HttpException.class)); - assertThat(exception.getMessage(), equalTo(HttpException.message(null, "Remote host terminated the handshake"))); + Throwable cause = exception.getCause(); assertThat(cause.getClass(), equalTo(SSLHandshakeException.class)); + assertThat(exception.getMessage(), equalTo(HttpException.message(null, cause.getMessage()))); } static class SimpleApiClient extends ApiClient { diff --git a/apiphany-okhttp/pom.xml b/apiphany-okhttp/pom.xml index 09f33260..64a80fcc 100644 --- a/apiphany-okhttp/pom.xml +++ b/apiphany-okhttp/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 apiphany-okhttp diff --git a/apiphany-okhttp/src/main/java/org/apiphany/http/OkHttpLibrary.java b/apiphany-okhttp/src/main/java/org/apiphany/http/OkHttpLibrary.java index 31a81554..6698338d 100644 --- a/apiphany-okhttp/src/main/java/org/apiphany/http/OkHttpLibrary.java +++ b/apiphany-okhttp/src/main/java/org/apiphany/http/OkHttpLibrary.java @@ -26,11 +26,11 @@ public class OkHttpLibrary { private static final LibraryVersion MINIMUM_VERSION = LibraryVersion.of(CLIENT_NAME, 4, 9, 0); /** - * The maximum OkHttp version this module supports, i.e. the highest version it was tested against: 4.12.0. + * The maximum OkHttp version this module supports, i.e. the highest version it was tested against: 4.12.1. *

* A newer runtime version is outside the tested range and is rejected by {@link #verifyVersion()}. */ - private static final LibraryVersion MAXIMUM_VERSION = LibraryVersion.of(CLIENT_NAME, 4, 12, 0); + private static final LibraryVersion MAXIMUM_VERSION = LibraryVersion.of(CLIENT_NAME, 4, 12, 1); /** * The OkHttp OkHttpClient class name. diff --git a/apiphany-okhttp/src/test/java/org/apiphany/http/OkHttpLibraryTest.java b/apiphany-okhttp/src/test/java/org/apiphany/http/OkHttpLibraryTest.java index cba4363a..fb97fef3 100644 --- a/apiphany-okhttp/src/test/java/org/apiphany/http/OkHttpLibraryTest.java +++ b/apiphany-okhttp/src/test/java/org/apiphany/http/OkHttpLibraryTest.java @@ -19,6 +19,9 @@ */ class OkHttpLibraryTest { + private static final String MIN_SUPPORTED_VERSION = "4.9.0"; + private static final String MAX_SUPPORTED_VERSION = "4.12.1"; + @Nested class IsPresentTests { @@ -83,7 +86,7 @@ class MinimumVersionTests { @Test void shouldReturnMinimumRequiredVersion() { - assertThat(OkHttpLibrary.minimumVersion().value(), equalTo("4.9.0")); + assertThat(OkHttpLibrary.minimumVersion().value(), equalTo(MIN_SUPPORTED_VERSION)); } @Test @@ -97,7 +100,7 @@ class MaximumVersionTests { @Test void shouldReturnMaximumSupportedVersion() { - assertThat(OkHttpLibrary.maximumVersion().value(), equalTo("4.12.0")); + assertThat(OkHttpLibrary.maximumVersion().value(), equalTo(MAX_SUPPORTED_VERSION)); } } diff --git a/apiphany-spring/pom.xml b/apiphany-spring/pom.xml index 66f2ce09..2badad0f 100644 --- a/apiphany-spring/pom.xml +++ b/apiphany-spring/pom.xml @@ -7,7 +7,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 apiphany-spring @@ -40,7 +40,6 @@ - 3.5.16 13.0.0 org.springframework.boot - spring-boot + spring-boot-restclient provided @@ -149,7 +147,6 @@ tools.jackson.core jackson-databind - ${jackson3.version} provided true @@ -157,7 +154,6 @@ tools.jackson.dataformat jackson-dataformat-xml - ${jackson3.version} provided true diff --git a/apiphany-spring/src/main/java/org/apiphany/client/http/AbstractSpringExchangeClient.java b/apiphany-spring/src/main/java/org/apiphany/client/http/AbstractSpringExchangeClient.java index 3891ea57..3a11d84e 100644 --- a/apiphany-spring/src/main/java/org/apiphany/client/http/AbstractSpringExchangeClient.java +++ b/apiphany-spring/src/main/java/org/apiphany/client/http/AbstractSpringExchangeClient.java @@ -270,7 +270,7 @@ protected HttpEntity createHttpEntity(final ApiRequest apiRequest, fin * @return the API response object */ protected ApiResponse buildResponse(final ApiRequest apiRequest, final ResponseEntity responseEntity) { - Map> headers = responseEntity.getHeaders(); + Map> headers = SpringHttpSupport.toHttpHeadersMap(responseEntity.getHeaders()); HttpStatus httpStatus = HttpStatus.fromCode(responseEntity.getStatusCode().value()); if (isTerminalRedirectWithLocation(httpStatus, headers)) { throw HttpException.builder().redirectLoop(httpStatus).build(); @@ -367,7 +367,7 @@ protected String extractResponseBody(final Throwable throwable) { @Override protected Map> extractResponseHeaders(final Throwable throwable) { return switch (throwable) { - case HttpStatusCodeException httpStatusCodeException -> Maps.safe(httpStatusCodeException.getResponseHeaders()); + case HttpStatusCodeException httpStatusCodeException -> SpringHttpSupport.toHttpHeadersMap(httpStatusCodeException.getResponseHeaders()); default -> super.extractResponseHeaders(throwable); }; } diff --git a/apiphany-spring/src/main/java/org/apiphany/client/http/RestTemplateExchangeClient.java b/apiphany-spring/src/main/java/org/apiphany/client/http/RestTemplateExchangeClient.java index 318aff07..6ddc37df 100644 --- a/apiphany-spring/src/main/java/org/apiphany/client/http/RestTemplateExchangeClient.java +++ b/apiphany-spring/src/main/java/org/apiphany/client/http/RestTemplateExchangeClient.java @@ -8,7 +8,7 @@ import org.apiphany.http.ResponseEntityExtractor; import org.apiphany.http.SpringHttpSupport; import org.apiphany.json.SpringJson; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RequestCallback; diff --git a/apiphany-spring/src/main/java/org/apiphany/client/http/SpringRestExchangeClient.java b/apiphany-spring/src/main/java/org/apiphany/client/http/SpringRestExchangeClient.java index db6ebdf8..3cb86f70 100644 --- a/apiphany-spring/src/main/java/org/apiphany/client/http/SpringRestExchangeClient.java +++ b/apiphany-spring/src/main/java/org/apiphany/client/http/SpringRestExchangeClient.java @@ -82,7 +82,13 @@ private RestClient.Builder customize(final RestClient.Builder restClientBuilder) if (null == SpringHttpSupport.getRequestFactory(restClientBuilder)) { restClientBuilder.requestFactory(getRequestFactory()); } - return restClientBuilder.messageConverters(getMessageConverters()); + return restClientBuilder.configureMessageConverters(clientBuilder -> { + clientBuilder.disableDefaults(); + clientBuilder.configureMessageConvertersList(converters -> { + converters.clear(); + converters.addAll(getMessageConverters()); + }); + }); } /** diff --git a/apiphany-spring/src/main/java/org/apiphany/http/CloseableHttpRequestFactory.java b/apiphany-spring/src/main/java/org/apiphany/http/CloseableHttpRequestFactory.java index c78d09d0..5758d7a5 100644 --- a/apiphany-spring/src/main/java/org/apiphany/http/CloseableHttpRequestFactory.java +++ b/apiphany-spring/src/main/java/org/apiphany/http/CloseableHttpRequestFactory.java @@ -279,6 +279,7 @@ public static CloseableHttpRequestFactory create(final ClientProperties clientPr // build the HTTP client and create the request factory with the appropriate settings from the client properties HttpClient httpClient = httpClientBuilder.build(); JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + requestFactory.enableCompression(false); requestFactory.setReadTimeout(JavaNetHttpClients.getTimeout(clientProperties.getTimeout(), Timeout::getRequest)); return CloseableHttpRequestFactory.of(requestFactory, httpClient); } diff --git a/apiphany-spring/src/main/java/org/apiphany/http/SpringHttpSupport.java b/apiphany-spring/src/main/java/org/apiphany/http/SpringHttpSupport.java index e19942fc..8a8f94e3 100644 --- a/apiphany-spring/src/main/java/org/apiphany/http/SpringHttpSupport.java +++ b/apiphany-spring/src/main/java/org/apiphany/http/SpringHttpSupport.java @@ -3,13 +3,15 @@ import java.io.File; import java.io.InputStream; import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.apiphany.io.OneShotInputStreamSupplier; import org.morphix.reflection.Constructors; import org.morphix.reflection.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpEntity; @@ -18,6 +20,7 @@ import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; +import org.springframework.util.LinkedCaseInsensitiveMap; import org.springframework.web.client.RestClient; /** @@ -151,6 +154,21 @@ public static boolean hasRequestFactory(final RestTemplateBuilder restTemplateBu return null != Fields.IgnoreAccess.get(restTemplateBuilder, "requestFactoryBuilder"); } + /** + * Transforms an {@link HttpHeaders} object to a map of headers. + * + * @param headers source headers + * @return HTTP headers + */ + public static Map> toHttpHeadersMap(final HttpHeaders headers) { + Map> httpHeaders = new LinkedCaseInsensitiveMap<>(); + if (null == headers) { + return httpHeaders; + } + headers.forEach((key, values) -> httpHeaders.put(key, new ArrayList<>(values))); + return httpHeaders; + } + /** * Hide constructor. */ diff --git a/apiphany-spring/src/main/java/org/apiphany/json/SpringJson.java b/apiphany-spring/src/main/java/org/apiphany/json/SpringJson.java index cafd5f75..d0aba915 100644 --- a/apiphany-spring/src/main/java/org/apiphany/json/SpringJson.java +++ b/apiphany-spring/src/main/java/org/apiphany/json/SpringJson.java @@ -1,61 +1,118 @@ package org.apiphany.json; -import java.util.Collections; import java.util.Locale; import java.util.Map; +import java.util.function.Consumer; import java.util.function.Function; import org.apiphany.client.ContentConverter; import org.apiphany.json.jackson2.Jackson2Library; import org.apiphany.json.jackson2.Jackson2SpringJson; +import org.apiphany.json.jackson3.Jackson3Library; +import org.apiphany.json.jackson3.Jackson3SpringJson; import org.morphix.lang.JavaObjects; +import org.morphix.lang.Nullables; import org.morphix.lang.collections.Iterables; import org.morphix.reflection.Constructors; import org.morphix.reflection.Fields; import org.morphix.runtime.OptionalLibrary; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverters; import org.springframework.web.client.RestClient; /** * Resolves the JSON request converter configured on a Spring HTTP client builder. *

- * A JSON-capable {@code HttpMessageConverter} contributes the mapper Spring built from the application's JSON library - * configuration. That mapper writes JSON request bodies as-is. A builder with no such converter has no converter, and - * the exchange client falls back to {@link JsonBuilder}. + * A JSON-capable {@link HttpMessageConverter} may expose a mapper configured by Spring (for example, from the + * application's Jackson configuration). When present, that converter is used by the Spring-based exchange clients to + * write JSON request bodies. If no usable JSON converter is found, the exchange client falls back to + * {@link JsonBuilder}. *

- * This class is library-agnostic. It verifies {@link Jackson2Library#isPresent()} before consulting - * {@link Jackson2SpringJson} for each JSON-capable message converter found on the builder. That presence check is what - * allows {@link Jackson2SpringJson} to use Jackson 2 types directly instead of reflection. + * This class resolves Jackson 2 and Jackson 3 converters. It verifies each library's presence before delegating to the + * corresponding resolver, allowing the library-specific code to reference Jackson types directly without reflective + * class loading. * * @author Radu Sebastian LAZIN */ public final class SpringJson { /** - * Field that holds the converters configured on a Spring client builder. + * Namespace class for field names. + * + * @author Radu Sebastian LAZIN */ - private static final String MESSAGE_CONVERTERS_FIELD_NAME = "messageConverters"; + public static class FieldName { + + /** + * Field name holding the message converters configured on a Spring client builder. + */ + private static final String MESSAGE_CONVERTERS = "messageConverters"; + + /** + * Field name holding the converters configurer on a {@link RestClient.Builder}. + */ + private static final String CONVERTERS_CONFIGURER = "convertersConfigurer"; + + /** + * Field name holding the JSON converter on a {@link HttpMessageConverters.ClientBuilder}. + */ + private static final String JSON_CONVERTER = "jsonConverter"; + + /** + * Hide constructor. + */ + private FieldName() { + throw Constructors.unsupportedOperationException(); + } + } + + /** + * Resolver function that resolves the appropriate content converter based on a Spring HTTP message converter. + * + * @param type that the content converter knows to convert + * + * @author Radu Sebastian LAZIN + */ + @FunctionalInterface + private interface ResolverFunction extends Function, ContentConverter> { + // empty + } /** * Maps each optional JSON library to the function that resolves a Spring message converter to a * {@link ContentConverter}. A resolver is used only when its library is present. */ - private static final Map, Function, ContentConverter>> CONVERTER_RESOLVERS_MAP = Map.of( - Jackson2Library.DESCRIPTOR, Jackson2SpringJson::converter); + private static final Map, ResolverFunction> CONVERTER_RESOLVERS_MAP = Map.of( + Jackson2Library.DESCRIPTOR, Jackson2SpringJson::converter, + Jackson3Library.DESCRIPTOR, Jackson3SpringJson::converter); /** * Returns the JSON request converter configured on the given {@link RestClient.Builder}, or {@code null} when the * builder has no usable JSON converter. + *

+ * This method supports both the traditional approach (where message converters are directly set on the builder via + * {@code messageConverters(...)}) and the new Spring Framework 7 approach (where converters are configured via + * {@link HttpMessageConverters.ClientBuilder} through a configurer). * * @param the content type the converter knows to convert - * * @param restClientBuilder the REST client builder * @return the JSON request converter, or {@code null} */ public static ContentConverter converter(final RestClient.Builder restClientBuilder) { - return converter(messageConverters(restClientBuilder)); + Iterable> messageConverters = messageConverters(restClientBuilder); + if (null != messageConverters) { + return converter(messageConverters); + } + Consumer convertersConfigurer = convertersConfigurer(restClientBuilder); + if (null == convertersConfigurer) { + return null; + } + HttpMessageConverters.ClientBuilder clientBuilder = HttpMessageConverters.forClient(); + convertersConfigurer.accept(clientBuilder); + HttpMessageConverter jsonConverter = jsonConverter(clientBuilder); + return resolveContentConverter(jsonConverter); } /** @@ -63,7 +120,6 @@ public static ContentConverter converter(final RestClient.Builder restCli * builder has no usable JSON converter. * * @param the content type the converter knows to convert - * * @param restTemplateBuilder the REST template builder * @return the JSON request converter, or {@code null} */ @@ -83,7 +139,7 @@ public static ContentConverter converter(final RestTemplateBuilder restTe static ContentConverter converter(final Iterable> messageConverters) { for (HttpMessageConverter messageConverter : Iterables.safe(messageConverters)) { if (supportsJson(messageConverter)) { - ContentConverter resolved = resolvedConverter(messageConverter); + ContentConverter resolved = resolveContentConverter(messageConverter); if (resolved != null) { return resolved; } @@ -93,19 +149,19 @@ static ContentConverter converter(final Iterable> } /** - * Returns the resolved content converter. + * Returns the resolved content converter from the given Spring message converter, or {@code null} if the converter is + * not a supported JSON converter. * * @param the content type the converter knows to convert - * * @param messageConverter any Spring message converter - * @return the resolved content converter + * @return the resolved content converter, or {@code null} */ - private static ContentConverter resolvedConverter(final HttpMessageConverter messageConverter) { - for (Map.Entry, Function, ContentConverter>> entry : CONVERTER_RESOLVERS_MAP.entrySet()) { + private static ContentConverter resolveContentConverter(final HttpMessageConverter messageConverter) { + for (Map.Entry, ResolverFunction> entry : CONVERTER_RESOLVERS_MAP.entrySet()) { OptionalLibrary optionalLibrary = entry.getKey(); if (optionalLibrary.isPresent()) { - Function, ContentConverter> resolverFunction = entry.getValue(); - ContentConverter resolved = JavaObjects.cast(resolverFunction.apply(messageConverter)); + ResolverFunction resolverFunction = JavaObjects.cast(entry.getValue()); + ContentConverter resolved = resolverFunction.apply(messageConverter); if (null != resolved) { return resolved; } @@ -115,24 +171,13 @@ private static ContentConverter resolvedConverter(final HttpMessageConver } /** - * Returns the converters already set on the builder. A builder that has not been given converters keeps a {@code null} - * field, and this method does not initialize the builder's defaults. - * - * @param builder the Spring client builder - * @return the configured converters, or {@code null} - */ - private static Iterable> messageConverters(final Object builder) { - if (null == builder) { - return Collections.emptyList(); - } - return Fields.IgnoreAccess.get(builder, MESSAGE_CONVERTERS_FIELD_NAME); - } - - /** - * Returns {@code true} when the converter writes JSON. + * Returns {@code true} when the converter supports JSON media types. + *

+ * A converter is considered to support JSON if any of its supported media types has subtype {@code json} or ends with + * {@code +json} (case-insensitive). * * @param converter the message converter - * @return {@code true} when one of the supported media types is JSON + * @return {@code true} when the converter supports JSON, {@code false} otherwise */ private static boolean supportsJson(final Object converter) { if (!(converter instanceof HttpMessageConverter httpMessageConverter)) { @@ -147,6 +192,41 @@ private static boolean supportsJson(final Object converter) { return false; } + /** + * Returns the converters already set on the builder. A builder that has not been given converters keeps a {@code null} + * field, and this method does not initialize the builder's defaults. + * + * @param builder the Spring client builder + * @return the configured converters, or {@code null} + */ + private static Iterable> messageConverters(final Object builder) { + return Nullables.>>whenNotNull(builder, + b -> Fields.IgnoreAccess.get(b, FieldName.MESSAGE_CONVERTERS)); + } + + /** + * Returns the converters configurer set on the builder. + * + * @param restClientBuilder the REST client builder + * @return the converters configurer, or {@code null} + */ + private static Consumer convertersConfigurer(final RestClient.Builder restClientBuilder) { + return Nullables.>whenNotNull(restClientBuilder, + b -> Fields.IgnoreAccess.get(b, FieldName.CONVERTERS_CONFIGURER)); + } + + /** + * Returns the JSON Spring message converter from the given client builder. + * + * @param the converter type + * @param clientBuilder the client builder + * @return the JSON Spring message converter, or {@code null} + */ + private static HttpMessageConverter jsonConverter(final HttpMessageConverters.ClientBuilder clientBuilder) { + return Nullables.>whenNotNull(clientBuilder, + b -> Fields.IgnoreAccess.get(b, FieldName.JSON_CONVERTER)); + } + /** * Hide constructor. */ diff --git a/apiphany-spring/src/main/java/org/apiphany/json/jackson2/Jackson2SpringJson.java b/apiphany-spring/src/main/java/org/apiphany/json/jackson2/Jackson2SpringJson.java index 0fc8058d..fd19dbe3 100644 --- a/apiphany-spring/src/main/java/org/apiphany/json/jackson2/Jackson2SpringJson.java +++ b/apiphany-spring/src/main/java/org/apiphany/json/jackson2/Jackson2SpringJson.java @@ -9,11 +9,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; /** - * Resolves a Jackson 2 {@code MappingJackson2HttpMessageConverter} to a {@link ContentConverter} that reads and writes + * Resolves a Jackson 2 {@link MappingJackson2HttpMessageConverter} to a {@link ContentConverter} that reads and writes * JSON with that converter's {@link ObjectMapper}. *

* This class uses Jackson 2 and Spring's Jackson 2 types directly. {@link SpringJson} only calls - * {@link #converter(HttpMessageConverter)} after verifying {@code Jackson2Library.isPresent()}, so this class is never + * {@link #converter(HttpMessageConverter)} after verifying {@link Jackson2Library#isPresent()}, so this class is never * loaded unless Jackson 2 is on the classpath. * * @author Radu Sebastian LAZIN @@ -22,13 +22,14 @@ public final class Jackson2SpringJson { /** * Returns a {@link ContentConverter} that reads and writes JSON with the given converter's {@link ObjectMapper}, or - * {@code null} when the converter is not a Jackson 2 HTTP message converter. + * {@code null} when the converter is not a {@link MappingJackson2HttpMessageConverter}. * * @param the content type the converter knows to convert * * @param messageConverter the Spring message converter * @return the JSON converter, or {@code null} */ + @SuppressWarnings("removal") public static ContentConverter converter(final HttpMessageConverter messageConverter) { if (messageConverter instanceof MappingJackson2HttpMessageConverter jackson2Converter) { return new Jackson2JsonHttpContentConverter<>(jackson2Converter.getObjectMapper()); diff --git a/apiphany-spring/src/main/java/org/apiphany/json/jackson3/Jackson3SpringJson.java b/apiphany-spring/src/main/java/org/apiphany/json/jackson3/Jackson3SpringJson.java new file mode 100644 index 00000000..a021d7ff --- /dev/null +++ b/apiphany-spring/src/main/java/org/apiphany/json/jackson3/Jackson3SpringJson.java @@ -0,0 +1,48 @@ +package org.apiphany.json.jackson3; + +import org.apiphany.client.ContentConverter; +import org.apiphany.json.SpringJson; +import org.morphix.reflection.Constructors; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; + +import tools.jackson.databind.json.JsonMapper; + +/** + * Resolves a {@link JacksonJsonHttpMessageConverter} to a {@link ContentConverter} that reads and writes JSON with that + * converter's {@link JsonMapper}. + *

+ * This class uses Jackson 3 and Spring's Jackson 3 types directly. {@link SpringJson} only calls + * {@link #converter(HttpMessageConverter)} after verifying {@link Jackson3Library#isPresent()}, so this class is never + * loaded unless Jackson 3 is on the classpath. + *

+ * Spring Framework 7 uses {@link JacksonJsonHttpMessageConverter} for Jackson 3; this resolver extracts the mapper via + * {@link JacksonJsonHttpMessageConverter#getMapper()}. + * + * @author Radu Sebastian LAZIN + */ +public final class Jackson3SpringJson { + + /** + * Returns a {@link ContentConverter} that reads and writes JSON with the given converter's {@link JsonMapper}, or + * {@code null} when the converter is not a {@link JacksonJsonHttpMessageConverter}. + * + * @param the content type the converter knows to convert + * @param messageConverter the Spring message converter + * @return the JSON converter, or {@code null} + */ + public static ContentConverter converter(final HttpMessageConverter messageConverter) { + if (messageConverter instanceof JacksonJsonHttpMessageConverter jacksonConverter) { + return new Jackson3JsonHttpContentConverter<>(jacksonConverter.getMapper()); + } + return null; + } + + /** + * Hide constructor. + */ + private Jackson3SpringJson() { + throw Constructors.unsupportedOperationException(); + } + +} diff --git a/apiphany-spring/src/test/java/org/apiphany/client/http/AbstractSpringExchangeClientTest.java b/apiphany-spring/src/test/java/org/apiphany/client/http/AbstractSpringExchangeClientTest.java index e366f476..f637bdf5 100644 --- a/apiphany-spring/src/test/java/org/apiphany/client/http/AbstractSpringExchangeClientTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/client/http/AbstractSpringExchangeClientTest.java @@ -537,7 +537,7 @@ void shouldSendStreamRequestWithoutBody() throws Exception { doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); doReturn(false).when(apiRequest).isStream(); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); ResponseEntity result = client.sendStreamRequest(apiRequest, httpEntity); @@ -558,7 +558,7 @@ void shouldSendStreamRequestWithInputStreamResponse() throws Exception { doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); doReturn(true).when(apiRequest).isStream(); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); ResponseEntity result = client.sendStreamRequest(apiRequest, httpEntity); @@ -579,7 +579,7 @@ void shouldCloseResponseAndWrapWhenExtractionFails() throws Exception { doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); doReturn(false).when(apiRequest).isStream(); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); HttpException exception = assertThrows(HttpException.class, () -> client.sendStreamRequest(apiRequest, httpEntity)); @@ -595,7 +595,7 @@ void shouldWrapIOExceptionWhenCreateRequestFails() throws Exception { doReturn(GET).when(apiRequest).getMethod(); doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); HttpException exception = assertThrows(HttpException.class, () -> client.sendStreamRequest(apiRequest, httpEntity)); diff --git a/apiphany-spring/src/test/java/org/apiphany/client/http/RestTemplateExchangeClientTest.java b/apiphany-spring/src/test/java/org/apiphany/client/http/RestTemplateExchangeClientTest.java index 4283cebc..9251714d 100644 --- a/apiphany-spring/src/test/java/org/apiphany/client/http/RestTemplateExchangeClientTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/client/http/RestTemplateExchangeClientTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.morphix.reflection.Fields; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; @@ -129,6 +129,7 @@ void shouldReturnDefaultMessageConverters() throws Exception { class JsonBodyTests { @Test + @SuppressWarnings("removal") void shouldWriteJsonWithTheObjectMapperFromTheRestTemplateBuilder() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); diff --git a/apiphany-spring/src/test/java/org/apiphany/client/http/SpringRestExchangeClientTest.java b/apiphany-spring/src/test/java/org/apiphany/client/http/SpringRestExchangeClientTest.java index c34f6033..03d692fa 100644 --- a/apiphany-spring/src/test/java/org/apiphany/client/http/SpringRestExchangeClientTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/client/http/SpringRestExchangeClientTest.java @@ -204,7 +204,7 @@ void shouldSendRequestWithoutBody() throws Exception { doReturn(new HttpHeaders()).when(response).getHeaders(); doReturn(new ByteArrayInputStream(new byte[0])).when(response).getBody(); stubRequestChain(HttpMethod.GET, TEST_URL); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); ApiRequest apiRequest = mock(ApiRequest.class); doReturn(GET).when(apiRequest).getMethod(); doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); @@ -248,7 +248,7 @@ void shouldSendRequestWithInputStreamResponse() throws Exception { doReturn(new HttpHeaders()).when(response).getHeaders(); doReturn(new ByteArrayInputStream(RESPONSE_BODY.getBytes())).when(response).getBody(); stubRequestChain(HttpMethod.GET, TEST_URL); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); ApiRequest apiRequest = mock(ApiRequest.class); doReturn(GET).when(apiRequest).getMethod(); doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); @@ -267,7 +267,7 @@ void shouldThrowWhenExchangeFails() { Error error = new OutOfMemoryError("exchange failed"); stubRequestChain(HttpMethod.GET, TEST_URL); doThrow(error).when(requestBodySpec).exchange(any(ExchangeFunction.class)); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); ApiRequest apiRequest = mock(ApiRequest.class); doReturn(GET).when(apiRequest).getMethod(); doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); @@ -284,7 +284,7 @@ void shouldReturnEmptyBodyForEmptyResponse() throws Exception { doReturn(new HttpHeaders()).when(response).getHeaders(); doReturn(new ByteArrayInputStream(new byte[0])).when(response).getBody(); stubRequestChain(HttpMethod.GET, TEST_URL); - HttpEntity httpEntity = new HttpEntity<>(null); + HttpEntity httpEntity = new HttpEntity<>((String) null); ApiRequest apiRequest = mock(ApiRequest.class); doReturn(GET).when(apiRequest).getMethod(); doReturn(URI.create(TEST_URL)).when(apiRequest).getUri(); @@ -320,6 +320,7 @@ private void stubExchange() { class JsonBodyTests { @Test + @SuppressWarnings("removal") void shouldWriteJsonWithTheObjectMapperFromTheRestClientBuilder() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); diff --git a/apiphany-spring/src/test/java/org/apiphany/http/HttpEntityRequestCallbackTest.java b/apiphany-spring/src/test/java/org/apiphany/http/HttpEntityRequestCallbackTest.java index f0e992a6..65e45940 100644 --- a/apiphany-spring/src/test/java/org/apiphany/http/HttpEntityRequestCallbackTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/http/HttpEntityRequestCallbackTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.verify; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -158,7 +159,8 @@ void shouldClearExistingRequestHeaders() throws Exception { callback.doWithRequest(request); - assertThat(requestHeaders.containsKey("X-PreExisting"), equalTo(false)); + Map> httpHeaders = SpringHttpSupport.toHttpHeadersMap(requestHeaders); + assertThat(httpHeaders.containsKey("X-PreExisting"), equalTo(false)); } } diff --git a/apiphany-spring/src/test/java/org/apiphany/http/SpringHttpSupportTest.java b/apiphany-spring/src/test/java/org/apiphany/http/SpringHttpSupportTest.java index 18a24f3f..b565d5e8 100644 --- a/apiphany-spring/src/test/java/org/apiphany/http/SpringHttpSupportTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/http/SpringHttpSupportTest.java @@ -15,7 +15,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpEntity; diff --git a/apiphany-spring/src/test/java/org/apiphany/json/SpringJsonTest.java b/apiphany-spring/src/test/java/org/apiphany/json/SpringJsonTest.java index f498a8ba..8f3cd11d 100644 --- a/apiphany-spring/src/test/java/org/apiphany/json/SpringJsonTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/json/SpringJsonTest.java @@ -10,7 +10,7 @@ import org.apiphany.client.ContentConverter; import org.apiphany.io.ContentType; import org.junit.jupiter.api.Test; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.http.MediaType; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; @@ -48,6 +48,7 @@ void shouldReturnNullWhenTheConvertersAreNotJackson() { } @Test + @SuppressWarnings("removal") void shouldReturnNullWhenNoConverterWritesJson() { MappingJackson2HttpMessageConverter text = new MappingJackson2HttpMessageConverter(new ObjectMapper()); text.setSupportedMediaTypes(List.of(MediaType.TEXT_PLAIN)); @@ -56,6 +57,7 @@ void shouldReturnNullWhenNoConverterWritesJson() { } @Test + @SuppressWarnings("removal") void shouldUseTheObjectMapperOfTheFirstJsonConverter() throws Exception { ObjectMapper textMapper = new ObjectMapper(); MappingJackson2HttpMessageConverter text = new MappingJackson2HttpMessageConverter(textMapper); @@ -73,6 +75,7 @@ void shouldUseTheObjectMapperOfTheFirstJsonConverter() throws Exception { } @Test + @SuppressWarnings("removal") void shouldConvertOnlyApplicationJson() { ContentConverter converter = SpringJson.converter(List.of(new MappingJackson2HttpMessageConverter())); @@ -82,6 +85,7 @@ void shouldConvertOnlyApplicationJson() { } @Test + @SuppressWarnings("removal") void shouldReadTheObjectMapperFromARestClientBuilder() throws Exception { ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); @@ -96,6 +100,7 @@ void shouldReadTheObjectMapperFromARestClientBuilder() throws Exception { } @Test + @SuppressWarnings("removal") void shouldReadTheObjectMapperFromARestTemplateBuilder() throws Exception { ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); diff --git a/apiphany-spring/src/test/java/org/apiphany/json/jackson2/Jackson2SpringJsonTest.java b/apiphany-spring/src/test/java/org/apiphany/json/jackson2/Jackson2SpringJsonTest.java index 9496f72c..5df87401 100644 --- a/apiphany-spring/src/test/java/org/apiphany/json/jackson2/Jackson2SpringJsonTest.java +++ b/apiphany-spring/src/test/java/org/apiphany/json/jackson2/Jackson2SpringJsonTest.java @@ -25,6 +25,7 @@ * * @author Radu Sebastian LAZIN */ +@SuppressWarnings("removal") class Jackson2SpringJsonTest { @Test diff --git a/apiphany-spring/src/test/java/org/apiphany/json/jackson3/Jackson3SpringJsonTest.java b/apiphany-spring/src/test/java/org/apiphany/json/jackson3/Jackson3SpringJsonTest.java new file mode 100644 index 00000000..053b7057 --- /dev/null +++ b/apiphany-spring/src/test/java/org/apiphany/json/jackson3/Jackson3SpringJsonTest.java @@ -0,0 +1,136 @@ +package org.apiphany.json.jackson3; + +import static org.apiphany.test.Assertions.assertDefaultConstructorThrows; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.apiphany.client.ContentConverter; +import org.apiphany.io.ContentType; +import org.junit.jupiter.api.Test; +import org.morphix.convert.ObjectConverterException; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; + +import tools.jackson.databind.PropertyNamingStrategies; +import tools.jackson.databind.json.JsonMapper; + +/** + * Tests for {@link Jackson3SpringJson}. + * + * @author Radu Sebastian LAZIN + */ +class Jackson3SpringJsonTest { + + @Test + void shouldReturnNullWhenTheConverterIsNull() { + assertThat(Jackson3SpringJson.converter(null), nullValue()); + } + + @Test + void shouldReturnNullWhenTheConverterIsNotJackson3() { + assertThat(Jackson3SpringJson.converter(new StringHttpMessageConverter()), nullValue()); + } + + @Test + void shouldResolveAConverterThatWritesWithTheMapper() throws Exception { + JsonMapper jsonMapper = JsonMapper.builder() + .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) + .build(); + JacksonJsonHttpMessageConverter jackson3Converter = new JacksonJsonHttpMessageConverter(jsonMapper); + + NamedPerson person = new NamedPerson(); + person.setFirstName("Ada"); + + ContentConverter converter = Jackson3SpringJson.converter(jackson3Converter); + + assertThat(converter.toString(person, ContentType.APPLICATION_JSON), + equalTo(jsonMapper.writeValueAsString(person))); + } + + @Test + void shouldConvertOnlyApplicationJson() { + ContentConverter converter = Jackson3SpringJson.converter(new JacksonJsonHttpMessageConverter()); + + assertThat(converter.isConvertible(ContentType.APPLICATION_JSON, null, null), equalTo(true)); + assertThat(converter.isConvertible(ContentType.TEXT_PLAIN, null, null), equalTo(false)); + assertThat(converter.isConvertible(null, null, null), equalTo(false)); + } + + @Test + void shouldReadAStringBodyWithTheMapper() throws Exception { + JsonMapper jsonMapper = JsonMapper.builder().build(); + JacksonJsonHttpMessageConverter jackson3Converter = new JacksonJsonHttpMessageConverter(jsonMapper); + ContentConverter converter = Jackson3SpringJson.converter(jackson3Converter); + + String json = jsonMapper.writeValueAsString("Ada"); + + assertThat(converter.from(json, ContentType.APPLICATION_JSON, String.class), equalTo("Ada")); + } + + @Test + void shouldReadAByteArrayBodyWithTheMapper() throws Exception { + JsonMapper jsonMapper = JsonMapper.builder().build(); + JacksonJsonHttpMessageConverter jackson3Converter = new JacksonJsonHttpMessageConverter(jsonMapper); + ContentConverter converter = Jackson3SpringJson.converter(jackson3Converter); + + byte[] json = jsonMapper.writeValueAsBytes("Ada"); + + assertThat(converter.from(json, ContentType.APPLICATION_JSON, String.class), equalTo("Ada")); + } + + @Test + void shouldReadAnInputStreamBodyWithTheMapper() throws Exception { + JsonMapper jsonMapper = JsonMapper.builder().build(); + JacksonJsonHttpMessageConverter jackson3Converter = new JacksonJsonHttpMessageConverter(jsonMapper); + ContentConverter converter = Jackson3SpringJson.converter(jackson3Converter); + + InputStream json = new ByteArrayInputStream(jsonMapper.writeValueAsBytes("Ada")); + + assertThat(converter.from(json, ContentType.APPLICATION_JSON, String.class), equalTo("Ada")); + } + + @Test + void shouldThrowWhenReadingAnUnsupportedBodyType() { + ContentConverter converter = Jackson3SpringJson.converter(new JacksonJsonHttpMessageConverter()); + + ObjectConverterException e = assertThrows(ObjectConverterException.class, + () -> converter.from(42, ContentType.APPLICATION_JSON, String.class)); + assertThat(e.getCause(), instanceOf(UnsupportedOperationException.class)); + } + + @Test + void shouldWrapAJsonProcessingExceptionWhenReading() { + ContentConverter converter = Jackson3SpringJson.converter(new JacksonJsonHttpMessageConverter()); + + assertThrows(ObjectConverterException.class, () -> converter.from("{", ContentType.APPLICATION_JSON, String.class)); + } + + @Test + void shouldPreventInstantiation() { + assertDefaultConstructorThrows(Jackson3SpringJson.class); + } + + /** + * Bean whose property name changes under snake case. + */ + static class NamedPerson { + + private String firstName; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + } + +} diff --git a/apiphany-test/pom.xml b/apiphany-test/pom.xml index d79156dd..a7ae4037 100644 --- a/apiphany-test/pom.xml +++ b/apiphany-test/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 apiphany-test diff --git a/integration/apiphany-httpclient5-tests/pom.xml b/integration/apiphany-httpclient5-tests/pom.xml index 870e33d3..d6c28d55 100644 --- a/integration/apiphany-httpclient5-tests/pom.xml +++ b/integration/apiphany-httpclient5-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml diff --git a/integration/apiphany-json-jackson2-tests/pom.xml b/integration/apiphany-json-jackson2-tests/pom.xml index 2135c7b1..313606c8 100644 --- a/integration/apiphany-json-jackson2-tests/pom.xml +++ b/integration/apiphany-json-jackson2-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml diff --git a/integration/apiphany-json-jackson3-tests/pom.xml b/integration/apiphany-json-jackson3-tests/pom.xml index ff3819cf..d1709567 100644 --- a/integration/apiphany-json-jackson3-tests/pom.xml +++ b/integration/apiphany-json-jackson3-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml diff --git a/integration/apiphany-json-no-dependency-tests/pom.xml b/integration/apiphany-json-no-dependency-tests/pom.xml index ce46d90f..32410b28 100644 --- a/integration/apiphany-json-no-dependency-tests/pom.xml +++ b/integration/apiphany-json-no-dependency-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml diff --git a/integration/apiphany-okhttp-tests/pom.xml b/integration/apiphany-okhttp-tests/pom.xml index b4ab5a45..c6d1561a 100644 --- a/integration/apiphany-okhttp-tests/pom.xml +++ b/integration/apiphany-okhttp-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml diff --git a/integration/apiphany-spring-no-client-tests/pom.xml b/integration/apiphany-spring-no-client-tests/pom.xml index abaabb17..68d0d99d 100644 --- a/integration/apiphany-spring-no-client-tests/pom.xml +++ b/integration/apiphany-spring-no-client-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml @@ -61,9 +61,8 @@ - org.springframework.boot - spring-boot + spring-boot-restclient ${spring.boot.version} diff --git a/integration/apiphany-spring-tests/pom.xml b/integration/apiphany-spring-tests/pom.xml index 2c0d4550..14dd7c47 100644 --- a/integration/apiphany-spring-tests/pom.xml +++ b/integration/apiphany-spring-tests/pom.xml @@ -8,7 +8,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 ../../pom.xml @@ -84,9 +84,8 @@ - org.springframework.boot - spring-boot + spring-boot-restclient ${spring.boot.version} diff --git a/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/RestTemplateExchangeClientObjectMapperIT.java b/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/RestTemplateExchangeClientObjectMapperIT.java index 5cca924f..11c99aae 100644 --- a/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/RestTemplateExchangeClientObjectMapperIT.java +++ b/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/RestTemplateExchangeClientObjectMapperIT.java @@ -20,7 +20,7 @@ import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.boot.restclient.RestTemplateBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @@ -48,6 +48,8 @@ class RestTemplateExchangeClientObjectMapperIT { .web(WebApplicationType.NONE) .run(); + private static final ObjectMapper OBJECT_MAPPER = CONTEXT.getBean(ObjectMapper.class); + @AfterAll static void closeContext() { CONTEXT.close(); @@ -64,8 +66,7 @@ void shouldWriteJsonRequestBodyWithTheObjectMapperBean() throws Exception { NamedPerson person = new NamedPerson(); person.setFirstName("Ada"); - ObjectMapper objectMapper = CONTEXT.getBean(ObjectMapper.class); - String json = objectMapper.writeValueAsString(person); + String json = OBJECT_MAPPER.writeValueAsString(person); assertThat(json, equalTo("{\"first_name\":\"Ada\"}")); TestApiClient apiClient = CONTEXT.getBean(TestApiClient.class); diff --git a/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientJsonMapperIT.java b/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientJsonMapperIT.java new file mode 100644 index 00000000..9585fdd0 --- /dev/null +++ b/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientJsonMapperIT.java @@ -0,0 +1,150 @@ +package org.apiphany.tests; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.apiphany.ApiClient; +import org.apiphany.client.ClientProperties; +import org.apiphany.client.http.SpringRestExchangeClient; +import org.apiphany.http.HttpHeader; +import org.apiphany.io.ContentType; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter; +import org.springframework.web.client.RestClient; + +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; + +import tools.jackson.databind.PropertyNamingStrategies; +import tools.jackson.databind.json.JsonMapper; + +/** + * Integration test proving {@link SpringRestExchangeClient} writes a JSON request body with the {@link JsonMapper} bean + * configured in a Spring Boot application. + * + * @author Radu Sebastian LAZIN + */ +class SpringRestExchangeClientJsonMapperIT { + + private static final String PATH = "/person"; + + @RegisterExtension + static final WireMockExtension wiremock = WireMockExtension.newInstance() + .options(options().dynamicPort()) + .build(); + + private static final ConfigurableApplicationContext CONTEXT = new SpringApplicationBuilder(TestApplication.class) + .web(WebApplicationType.NONE) + .run(); + + private static final JsonMapper JSON_MAPPER = CONTEXT.getBean(JsonMapper.class); + + @AfterAll + static void closeContext() { + CONTEXT.close(); + } + + @Test + @SuppressWarnings("resource") + void shouldWriteJsonRequestBodyWithTheJsonMapperBean() throws Exception { + wiremock.stubFor(post(urlEqualTo(PATH)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/plain") + .withBody("ok"))); + + NamedPerson person = new NamedPerson(); + person.setFirstName("Ada"); + String json = JSON_MAPPER.writeValueAsString(person); + assertThat(json, equalTo("{\"first_name\":\"Ada\"}")); + + TestApiClient apiClient = CONTEXT.getBean(TestApiClient.class); + String response = apiClient.postPerson(wiremock.baseUrl() + PATH, person); + + assertThat(response, equalTo("ok")); + wiremock.verify(postRequestedFor(urlEqualTo(PATH)) + .withHeader("Content-Type", WireMock.equalTo("application/json")) + .withRequestBody(WireMock.equalTo(json))); + } + + /** + * Bean whose property name changes under the application {@link JsonMapper}. + */ + static class NamedPerson { + + private String firstName; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + } + + static class TestApiClient extends ApiClient { + + TestApiClient(final SpringRestExchangeClient springRestExchangeClient) { + super(springRestExchangeClient); + } + + String postPerson(final String url, final NamedPerson person) { + return client() + .http() + .post() + .url(url) + .header(HttpHeader.CONTENT_TYPE, ContentType.APPLICATION_JSON) + .body(person) + .retrieve(String.class) + .orRethrow(); + } + } + + @SpringBootConfiguration + @EnableAutoConfiguration + static class TestApplication { + + @Bean + JsonMapper jsonMapper() { + return JsonMapper.builder() + .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) + .build(); + } + + @Bean + ClientProperties clientProperties() { + return ClientProperties.defaults(); + } + + @Bean + RestClient.Builder restClientBuilder(final JsonMapper jsonMapper) { + return RestClient.builder().configureMessageConverters(messageConverters -> messageConverters.disableDefaults() + .withJsonConverter(new JacksonJsonHttpMessageConverter(jsonMapper))); + } + + @Bean + SpringRestExchangeClient springRestExchangeClient(final ClientProperties clientProperties, + final RestClient.Builder restClientBuilder) { + return new SpringRestExchangeClient(clientProperties, restClientBuilder); + } + + @Bean + TestApiClient testApiClient(final SpringRestExchangeClient springRestExchangeClient) { + return new TestApiClient(springRestExchangeClient); + } + } +} diff --git a/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientObjectMapperIT.java b/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientObjectMapperIT.java index dfbcd371..aa731315 100644 --- a/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientObjectMapperIT.java +++ b/integration/apiphany-spring-tests/src/test/java/org/apiphany/tests/SpringRestExchangeClientObjectMapperIT.java @@ -48,6 +48,8 @@ class SpringRestExchangeClientObjectMapperIT { .web(WebApplicationType.NONE) .run(); + private static final ObjectMapper OBJECT_MAPPER = CONTEXT.getBean(ObjectMapper.class); + @AfterAll static void closeContext() { CONTEXT.close(); @@ -64,8 +66,7 @@ void shouldWriteJsonRequestBodyWithTheObjectMapperBean() throws Exception { NamedPerson person = new NamedPerson(); person.setFirstName("Ada"); - ObjectMapper objectMapper = CONTEXT.getBean(ObjectMapper.class); - String json = objectMapper.writeValueAsString(person); + String json = OBJECT_MAPPER.writeValueAsString(person); assertThat(json, equalTo("{\"first_name\":\"Ada\"}")); TestApiClient apiClient = CONTEXT.getBean(TestApiClient.class); diff --git a/pom.xml b/pom.xml index d1c5dfd7..c7ec5963 100644 --- a/pom.xml +++ b/pom.xml @@ -12,7 +12,7 @@ io.github.raduking apiphany-parent - 1.2.23 + 1.3.0 pom ${project.groupId}:${project.artifactId} @@ -63,14 +63,14 @@ 1.0.47 - 1.15.11 - 2.21.4 - 3.1.3 - 2.0.18 - 5.6.3 - 4.12.0 - 6.2.19 - 3.5.16 + 1.17.2 + 2.21.7 + 3.1.7 + 2.0.20 + 5.6.5 + 4.12.1 + 7.0.10 + 4.1.2 21 @@ -84,12 +84,12 @@ 3.0 6.1.3 - 5.23.0 - 1.5.34 - 7.1.0 + 5.24.0 + 1.5.38 + 7.1.2 2.0.5 - 4.3.1 - 10.9.1 + 4.4.0 + 10.10 11.38.2 3.13.2 @@ -100,26 +100,26 @@ 3.2.8 - 0.11.0 + 0.12.0 - 1.30.0 + 1.30.1 1.2.3 - 0.8.15 + 0.8.16 3.9.0 - 3.15.0 - 3.5.6 - 3.5.6 + 3.16.0 + 3.6.1 + 3.6.1 3.5.0 1.3.0 3.4.0 3.5.1 3.12.0 - 3.1.4 - 3.10.0 - 3.6.3 + 3.2.0 + 3.10.4 + 3.6.4 3.6.3 3.2.0