From 4db12806d1d2fff9cd2d5cecb53ed5cf5eb39978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Deleuze?= Date: Tue, 1 Apr 2025 16:49:19 +0200 Subject: [PATCH 1/3] Revert "Add a requiredExchange extension to RestClient" This reverts commit dcb9383ba1239aa949983f5ef9e6dcf9cad4e98a. See gh-34692 --- .../web/client/RestClientExtensions.kt | 16 ++----------- .../web/client/RestClientExtensionsTests.kt | 23 +------------------ 2 files changed, 3 insertions(+), 36 deletions(-) diff --git a/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt b/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt index 5159993951..12092af8df 100644 --- a/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt +++ b/spring-web/src/main/kotlin/org/springframework/web/client/RestClientExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2002-2025 the original author or authors. + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ package org.springframework.web.client import org.springframework.core.ParameterizedTypeReference import org.springframework.http.ResponseEntity -import org.springframework.web.client.RestClient.RequestHeadersSpec -import org.springframework.web.client.RestClient.RequestHeadersSpec.ExchangeFunction /** * Extension for [RestClient.RequestBodySpec.body] providing a `bodyWithType(...)` variant @@ -53,15 +51,6 @@ inline fun RestClient.ResponseSpec.body(): T? = inline fun RestClient.ResponseSpec.requiredBody(): T = body(object : ParameterizedTypeReference() {}) ?: throw NoSuchElementException("Response body is required") -/** - * Extension for [RestClient.RequestHeadersSpec.exchange] providing a `requiredExchange(...)` variant with a - * non-nullable return value. - * @throws NoSuchElementException if there is no response value - * @since 6.2.6 - */ -fun RequestHeadersSpec<*>.requiredExchange(exchangeFunction: ExchangeFunction, close: Boolean = true): T = - exchange(exchangeFunction, close) ?: throw NoSuchElementException("Response value is required") - /** * Extension for [RestClient.ResponseSpec.toEntity] providing a `toEntity()` variant * leveraging Kotlin reified type parameters. This extension is not subject to type @@ -71,5 +60,4 @@ fun RequestHeadersSpec<*>.requiredExchange(exchangeFunction: ExchangeFu * @since 6.1 */ inline fun RestClient.ResponseSpec.toEntity(): ResponseEntity = - toEntity(object : ParameterizedTypeReference() {}) - + toEntity(object : ParameterizedTypeReference() {}) \ No newline at end of file diff --git a/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt b/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt index 703398e2c4..6e91590166 100644 --- a/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt +++ b/spring-web/src/test/kotlin/org/springframework/web/client/RestClientExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2002-2025 the original author or authors. + * Copyright 2002-2024 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,9 @@ package org.springframework.web.client import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.springframework.core.ParameterizedTypeReference -import org.springframework.http.HttpRequest -import org.springframework.web.client.RestClient.RequestHeadersSpec /** * Mock object based tests for [RestClient] Kotlin extensions @@ -62,24 +59,6 @@ class RestClientExtensionsTests { assertThrows { responseSpec.requiredBody() } } - @Test - fun `RequestHeadersSpec#requiredExchange`() { - val foo = Foo() - every { requestBodySpec.exchange(any>(), any()) } returns foo - val exchangeFunction: (HttpRequest, RequestHeadersSpec.ConvertibleClientHttpResponse) -> Foo? = - { _, _ -> foo } - val value = requestBodySpec.requiredExchange(exchangeFunction) - assertThat(value).isEqualTo(foo) - } - - @Test - fun `RequestHeadersSpec#requiredExchange with null response throws NoSuchElementException`() { - every { requestBodySpec.exchange(any>(), any()) } returns null - val exchangeFunction: (HttpRequest, RequestHeadersSpec.ConvertibleClientHttpResponse) -> Foo? = - { _, _ -> null } - assertThrows { requestBodySpec.requiredExchange(exchangeFunction) } - } - @Test fun `ResponseSpec#toEntity with reified type parameters`() { responseSpec.toEntity>() From d9047d39e6a2b9adfe75718fa07f13e3bd615efb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Deleuze?= Date: Tue, 1 Apr 2025 16:44:07 +0200 Subject: [PATCH 2/3] Refine ExchangeFunction Javadoc See gh-34692 --- .../springframework/web/client/RestClient.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/client/RestClient.java b/spring-web/src/main/java/org/springframework/web/client/RestClient.java index 1b7016d77e..475f8c864b 100644 --- a/spring-web/src/main/java/org/springframework/web/client/RestClient.java +++ b/spring-web/src/main/java/org/springframework/web/client/RestClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2002-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -649,8 +649,8 @@ public interface RestClient { ResponseSpec retrieve(); /** - * Exchange the {@link ClientHttpResponse} for a type {@code T}. This - * can be useful for advanced scenarios, for example to decode the + * Exchange the {@link ClientHttpResponse} for a value of type {@code T}. + * This can be useful for advanced scenarios, for example to decode the * response differently depending on the response status: *
 		 * Person person = client.get()
@@ -670,7 +670,7 @@ public interface RestClient {
 		 * function has been invoked.
 		 * @param exchangeFunction the function to handle the response with
 		 * @param  the type the response will be transformed to
-		 * @return the value returned from the exchange function
+		 * @return the value returned from the exchange function, potentially {@code null}
 		 */
 		@Nullable
 		default  T exchange(ExchangeFunction exchangeFunction) {
@@ -678,8 +678,8 @@ public interface RestClient {
 		}
 
 		/**
-		 * Exchange the {@link ClientHttpResponse} for a type {@code T}. This
-		 * can be useful for advanced scenarios, for example to decode the
+		 * Exchange the {@link ClientHttpResponse} for a value of type {@code T}.
+		 * This can be useful for advanced scenarios, for example to decode the
 		 * response differently depending on the response status:
 		 * 
 		 * Person person = client.get()
@@ -702,7 +702,7 @@ public interface RestClient {
 		 * @param close {@code true} to close the response after
 		 * {@code exchangeFunction} is invoked, {@code false} to keep it open
 		 * @param  the type the response will be transformed to
-		 * @return the value returned from the exchange function
+		 * @return the value returned from the exchange function, potentially {@code null}
 		 */
 		@Nullable
 		 T exchange(ExchangeFunction exchangeFunction, boolean close);
@@ -716,10 +716,10 @@ public interface RestClient {
 		interface ExchangeFunction {
 
 			/**
-			 * Exchange the given response into a type {@code T}.
+			 * Exchange the given response into a value of type {@code T}.
 			 * @param clientRequest the request
 			 * @param clientResponse the response
-			 * @return the exchanged type
+			 * @return the exchanged value, potentially {@code null}
 			 * @throws IOException in case of I/O errors
 			 */
 			@Nullable

From 671d972454dc594a84070e728f0b8eae1ed2a427 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Deleuze?=
 
Date: Wed, 2 Apr 2025 14:08:08 +0200
Subject: [PATCH 3/3] Add
 RestClient.RequestHeadersSpec#exchangeForRequiredValue

This commit adds a variant to RestClient.RequestHeadersSpec#exchange
suitable for functions returning non-null values.

Closes gh-34692
---
 .../web/client/DefaultRestClient.java         |  7 ++
 .../web/client/RestClient.java                | 75 +++++++++++++++++++
 .../client/RestClientIntegrationTests.java    | 36 ++++++++-
 3 files changed, 117 insertions(+), 1 deletion(-)

diff --git a/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java b/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java
index b877ec388e..d022774e70 100644
--- a/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java
+++ b/spring-web/src/main/java/org/springframework/web/client/DefaultRestClient.java
@@ -533,6 +533,13 @@ final class DefaultRestClient implements RestClient {
 			return exchangeInternal(exchangeFunction, close);
 		}
 
+		@Override
+		public  T exchangeForRequiredValue(RequiredValueExchangeFunction exchangeFunction, boolean close) {
+			T value = exchangeInternal(exchangeFunction, close);
+			Assert.state(value != null, "The exchanged value must not be null");
+			return value;
+		}
+
 		@Nullable
 		private  T exchangeInternal(ExchangeFunction exchangeFunction, boolean close) {
 			Assert.notNull(exchangeFunction, "ExchangeFunction must not be null");
diff --git a/spring-web/src/main/java/org/springframework/web/client/RestClient.java b/spring-web/src/main/java/org/springframework/web/client/RestClient.java
index 475f8c864b..af9c6722e5 100644
--- a/spring-web/src/main/java/org/springframework/web/client/RestClient.java
+++ b/spring-web/src/main/java/org/springframework/web/client/RestClient.java
@@ -671,12 +671,41 @@ public interface RestClient {
 		 * @param exchangeFunction the function to handle the response with
 		 * @param  the type the response will be transformed to
 		 * @return the value returned from the exchange function, potentially {@code null}
+		 * @see RequestHeadersSpec#exchangeForRequiredValue(RequiredValueExchangeFunction)
 		 */
 		@Nullable
 		default  T exchange(ExchangeFunction exchangeFunction) {
 			return exchange(exchangeFunction, true);
 		}
 
+		/**
+		 * Exchange the {@link ClientHttpResponse} for a value of type {@code T}.
+		 * This can be useful for advanced scenarios, for example to decode the
+		 * response differently depending on the response status:
+		 * 
+		 * Person person = client.get()
+		 *     .uri("/people/1")
+		 *     .accept(MediaType.APPLICATION_JSON)
+		 *     .exchange((request, response) -> {
+		 *         if (response.getStatusCode().equals(HttpStatus.OK)) {
+		 *             return deserialize(response.getBody());
+		 *         }
+		 *         else {
+		 *             throw new BusinessException();
+		 *         }
+		 *     });
+		 * 
+ *

Note: The response is + * {@linkplain ClientHttpResponse#close() closed} after the exchange + * function has been invoked. + * @param exchangeFunction the function to handle the response with + * @param the type the response will be transformed to + * @return the value returned from the exchange function, never {@code null} + */ + default T exchangeForRequiredValue(RequiredValueExchangeFunction exchangeFunction) { + return exchangeForRequiredValue(exchangeFunction, true); + } + /** * Exchange the {@link ClientHttpResponse} for a value of type {@code T}. * This can be useful for advanced scenarios, for example to decode the @@ -703,10 +732,40 @@ public interface RestClient { * {@code exchangeFunction} is invoked, {@code false} to keep it open * @param the type the response will be transformed to * @return the value returned from the exchange function, potentially {@code null} + * @see RequestHeadersSpec#exchangeForRequiredValue(RequiredValueExchangeFunction, boolean) */ @Nullable T exchange(ExchangeFunction exchangeFunction, boolean close); + /** + * Exchange the {@link ClientHttpResponse} for a value of type {@code T}. + * This can be useful for advanced scenarios, for example to decode the + * response differently depending on the response status: + *

+		 * Person person = client.get()
+		 *     .uri("/people/1")
+		 *     .accept(MediaType.APPLICATION_JSON)
+		 *     .exchange((request, response) -> {
+		 *         if (response.getStatusCode().equals(HttpStatus.OK)) {
+		 *             return deserialize(response.getBody());
+		 *         }
+		 *         else {
+		 *             throw new BusinessException();
+		 *         }
+		 *     });
+		 * 
+ *

Note: If {@code close} is {@code true}, + * then the response is {@linkplain ClientHttpResponse#close() closed} + * after the exchange function has been invoked. When set to + * {@code false}, the caller is responsible for closing the response. + * @param exchangeFunction the function to handle the response with + * @param close {@code true} to close the response after + * {@code exchangeFunction} is invoked, {@code false} to keep it open + * @param the type the response will be transformed to + * @return the value returned from the exchange function, never {@code null} + */ + T exchangeForRequiredValue(RequiredValueExchangeFunction exchangeFunction, boolean close); + /** * Defines the contract for {@link #exchange(ExchangeFunction)}. @@ -726,6 +785,22 @@ public interface RestClient { T exchange(HttpRequest clientRequest, ConvertibleClientHttpResponse clientResponse) throws IOException; } + /** + * Variant of {@link ExchangeFunction} returning a non-null required value. + * @param the type the response will be transformed to + */ + @FunctionalInterface + interface RequiredValueExchangeFunction extends ExchangeFunction { + + /** + * Exchange the given response into a value of type {@code T}. + * @param clientRequest the request + * @param clientResponse the response + * @return the exchanged value, never {@code null} + * @throws IOException in case of I/O errors + */ + T exchange(HttpRequest clientRequest, ConvertibleClientHttpResponse clientResponse) throws IOException; + } /** * Extension of {@link ClientHttpResponse} that can convert the body. diff --git a/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java index 916116fa45..d33dd2d32e 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestClientIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2024 the original author or authors. + * Copyright 2002-2025 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,6 +58,7 @@ import org.springframework.web.testfixture.xml.Pojo; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.params.provider.Arguments.argumentSet; @@ -766,6 +767,39 @@ class RestClientIntegrationTests { expectRequest(request -> assertThat(request.getPath()).isEqualTo("/greeting")); } + @ParameterizedRestClientTest + void exchangeForRequiredValue(ClientHttpRequestFactory requestFactory) { + startServer(requestFactory); + + prepareResponse(response -> response.setBody("Hello Spring!")); + + String result = this.restClient.get() + .uri("/greeting") + .header("X-Test-Header", "testvalue") + .exchangeForRequiredValue((request, response) -> new String(RestClientUtils.getBody(response), UTF_8)); + + assertThat(result).isEqualTo("Hello Spring!"); + + expectRequestCount(1); + expectRequest(request -> { + assertThat(request.getHeader("X-Test-Header")).isEqualTo("testvalue"); + assertThat(request.getPath()).isEqualTo("/greeting"); + }); + } + + @ParameterizedRestClientTest + @SuppressWarnings("DataFlowIssue") + void exchangeForNullRequiredValue(ClientHttpRequestFactory requestFactory) { + startServer(requestFactory); + + prepareResponse(response -> response.setBody("Hello Spring!")); + + assertThatIllegalStateException().isThrownBy(() -> this.restClient.get() + .uri("/greeting") + .header("X-Test-Header", "testvalue") + .exchangeForRequiredValue((request, response) -> null)); + } + @ParameterizedRestClientTest void requestInitializer(ClientHttpRequestFactory requestFactory) { startServer(requestFactory);