Add resttemplate-to-restclient module: RestTemplate deprecation on Spring Framework 7.1 / Boot 4.2.0 vs 4.1.3, method mapping, exchange() trap, bridge URI encoding, RestTestClient, OpenRewrite recipe run, with real transcripts

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7M7FEdeEm3APj16Bu
This commit is contained in:
Claude
2026-11-21 21:26:48 +05:30
parent 5f85ec8d53
commit cbcfb05e35
77 changed files with 2187 additions and 0 deletions
+1
View File
@@ -9,6 +9,7 @@ files.
| Directory | Article | What it demonstrates | | Directory | Article | What it demonstrates |
|---|---|---| |---|---|---|
| [`resttemplate-to-restclient/`](resttemplate-to-restclient) | [RestTemplate Is Deprecated in Spring Framework 7.1: Migrate to RestClient (and TestRestTemplate to RestTestClient)](https://ankurm.com/resttemplate-to-restclient-migration-guide/) | the `[removal]` warnings on 4.2.0 vs none on 4.1.3, every `RestTemplate` method next to its `RestClient` call on one real server, `exchange()` that stops throwing, the `RestClient.create(restTemplate)` bridge that changes URI encoding, PATCH and `User-Agent` of each default stack, an interceptor that eats the body, `TestRestTemplate` vs `RestTestClient`, and the OpenRewrite recipe's output run for real |
| [`email/`](email) | [Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing](https://ankurm.com/sending-emails-in-spring-boot-3-a-complete-guide/) | the MIME tree of six message shapes (`multipart/mixed` > `related` > `alternative`, and `addInline` before `setText` putting the image first), Thymeleaf HTML and TEXT templates (`[[...]]` still HTML-escapes in TEXT mode), Devanagari subjects as encoded-words and a wrong `defaultEncoding` turning them into `?`, one `send` per message (5 connections) vs the varargs `send` (1), `@Async` returning in milliseconds and a `void @Async` failure that never reaches the caller, a server that never greets blocking forever until `mail.smtp.timeout` is set (`connectiontimeout` does not help), `starttls.enable` authenticating in plain text while `starttls.required` refuses, an email still sent when the transaction rolls back unless it waits for `AFTER_COMMIT`, all against GreenMail on Spring Boot 4.1.2 | | [`email/`](email) | [Sending Emails in Spring Boot 4: SMTP, HTML Templates, Attachments and Testing](https://ankurm.com/sending-emails-in-spring-boot-3-a-complete-guide/) | the MIME tree of six message shapes (`multipart/mixed` > `related` > `alternative`, and `addInline` before `setText` putting the image first), Thymeleaf HTML and TEXT templates (`[[...]]` still HTML-escapes in TEXT mode), Devanagari subjects as encoded-words and a wrong `defaultEncoding` turning them into `?`, one `send` per message (5 connections) vs the varargs `send` (1), `@Async` returning in milliseconds and a `void @Async` failure that never reaches the caller, a server that never greets blocking forever until `mail.smtp.timeout` is set (`connectiontimeout` does not help), `starttls.enable` authenticating in plain text while `starttls.required` refuses, an email still sent when the transaction rolls back unless it waits for `AFTER_COMMIT`, all against GreenMail on Spring Boot 4.1.2 |
| [`log4j2-levels/`](log4j2-levels) | [Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime](https://ankurm.com/log4j2-logging-levels-complete-guide/) | the threshold rule printed as a matrix, a level inherited from the nearest configured ancestor, a logger with its own appender and default additivity printing every line twice, custom `DIAG`/`PERF` levels between the standard ones, `/actuator/loggers` rejecting a custom level and a `null` reset landing on the root's level instead of the XML's, `logging.level.*` beating the XML and a custom level in that property stopping the app at startup, argument `toString()` counts for six call shapes, and Logback plus Log4j2 on one classpath silently handing everything to Logback | | [`log4j2-levels/`](log4j2-levels) | [Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime](https://ankurm.com/log4j2-logging-levels-complete-guide/) | the threshold rule printed as a matrix, a level inherited from the nearest configured ancestor, a logger with its own appender and default additivity printing every line twice, custom `DIAG`/`PERF` levels between the standard ones, `/actuator/loggers` rejecting a custom level and a `null` reset landing on the root's level instead of the XML's, `logging.level.*` beating the XML and a custom level in that property stopping the app at startup, argument `toString()` counts for six call shapes, and Logback plus Log4j2 on one classpath silently handing everything to Logback |
| [`idempotency/`](idempotency) | [Idempotency Keys for POST APIs in Spring Boot (Stripe-Style) with Redis and Postgres](https://ankurm.com/idempotency-keys-spring-boot-redis-postgres/) | one servlet filter and two interchangeable stores: a retried POST after a client timeout creating two payments without a key and one with; 400 / 422 / 409 and replay with `Idempotent-Replayed`; ten simultaneous duplicates (nine `409` on Redis, nine replays on Postgres because the second `INSERT` waits on the first's uncommitted row); a crash after the payment commits leaving Redis with a stuck lock and then a duplicate payment, and Postgres with neither; a handler slower than the Redis lock finishing with nothing stored; the legacy `Asia/Calcutta` zone id that PostgreSQL 16 refuses at connect time | | [`idempotency/`](idempotency) | [Idempotency Keys for POST APIs in Spring Boot (Stripe-Style) with Redis and Postgres](https://ankurm.com/idempotency-keys-spring-boot-redis-postgres/) | one servlet filter and two interchangeable stores: a retried POST after a client timeout creating two payments without a key and one with; 400 / 422 / 409 and replay with `Idempotent-Replayed`; ten simultaneous duplicates (nine `409` on Redis, nine replays on Postgres because the second `INSERT` waits on the first's uncommitted row); a crash after the payment commits leaving Redis with a stuck lock and then a duplicate payment, and Postgres with neither; a handler slower than the Redis lock finishing with nothing stored; the legacy `Asia/Calcutta` zone id that PostgreSQL 16 refuses at connect time |
+29
View File
@@ -0,0 +1,29 @@
# resttemplate-to-restclient
Companion module for the ankurm.com article *RestTemplate Is Deprecated in Spring Framework 7.1: Migrate to RestClient (and TestRestTemplate to RestTestClient)*.
Everything runs against **Spring Boot 4.2.0** (Spring Framework 7.1.0) and, for the before/after comparison, against **4.1.3** (Spring Framework 7.0.11). JDK 25 (Temurin 25.0.5), Maven 3.9.
| Path | What it is |
|---|---|
| `src/main/.../StudentController` | the real server every client calls: CRUD, a 404, a 500, `/whoami` (echoes the headers the server received), `/search` (echoes the raw query string), `/slow` |
| `src/main/.../LegacyStudentClient`, `StudentClient` | the same two operations on `RestTemplate` and on `RestClient` |
| `src/main/.../RestClientConfig` | timeouts and an interceptor on `RestClient`, using `HttpClientSettings` |
| `src/test/.../MethodMappingTest` | every row of the method-mapping table: the `RestTemplate` call and the `RestClient` call side by side, same server |
| `src/test/.../ErrorHandlingTest` | exception types and messages for 404, 500 and a refused connection; a custom `ResponseErrorHandler` moved to `defaultStatusHandler` / `onStatus` |
| `src/test/.../ExchangeTrapTest` | `exchange()` on `RestClient` does not apply the default status handlers |
| `src/test/.../BridgeTest` | `RestClient.create(restTemplate)`: what it copies (interceptors, error handler, request factory) and the URI-encoding change it does not carry over |
| `src/test/.../RequestFactoryTest` | the default HTTP stack of each client as the server sees it (`User-Agent`), and `PATCH` |
| `src/test/.../InterceptorBufferingTest` | an interceptor that reads the response body, with and without buffering |
| `src/test/.../TimeoutsTest` | `spring.http.clients.*` on `RestClient.Builder` and `RestTemplateBuilder`, and the programmatic `HttpClientSettings` form |
| `src/test/.../TestClientMigrationTest` | `TestRestTemplate` and `RestTestClient` asserting the same things |
| `src/test/.../MockServerTest` | `MockRestServiceServer.bindTo(...)` on a `RestTemplate` and on a `RestClient.Builder` |
| `src/test/.../BuilderBeansTest`, `ConfiguredClientTest` | which client beans Boot registers; the `RestClientConfig` bean |
| `src/test/.../RecipeOutputTest` + `recipe/RemoteClient.java` | the class OpenRewrite generated from `src/recipe/before/RemoteClient.java`, run against the real server |
| `src/broken/*.java` | not built; `scripts/compile-broken.sh` compiles each with `-Xlint:deprecation` and keeps the compiler's own message |
| `scripts/probe-jars.sh`, `scripts/probe-properties.sh` | read the `@Deprecated(since, forRemoval)` annotations and the HTTP-client property metadata straight from the published jars |
| `scripts/openrewrite.sh` | runs `io.moderne.java.spring.boot3.MigrateRestTemplateToRestClient` on a scratch copy and stores the diff |
| `output/` | every transcript quoted in the article; `./scripts/run-all.sh` regenerates them (files suffixed `-on-4.1.3` are the baseline) |
Run: `./scripts/run-all.sh`. Timing figures in `output/09-timeouts.txt` are reported in coarse buckets because they drift between runs.
There is deliberately no `docs/` folder: the explanations live in the article.
@@ -0,0 +1,57 @@
# 01-method-mapping (Spring Boot 4.1.3, JDK 25)
server: StudentController on http://localhost:<random port>, seeded with 1=Asha, 2=Ravi
RestTemplate getForObject(url, Student.class, 1)
-> Student[id=1, name=Asha]
RestClient get().uri(url, 1).retrieve().body(Student.class)
-> Student[id=1, name=Asha] same result: true
RestTemplate getForEntity(url, Student.class, 2)
-> 200 OK application/json Student[id=2, name=Ravi]
RestClient get().uri(url, 2).retrieve().toEntity(Student.class)
-> 200 OK application/json Student[id=2, name=Ravi] same result: true
RestTemplate postForObject(url, request, Student.class)
-> Student[id=3, name=Meera]
RestClient post().uri(url).body(request).retrieve().body(Student.class)
-> Student[id=3, name=Meera] same result: true
RestTemplate postForEntity(url, request, Student.class)
-> 201 CREATED /students/3 Student[id=3, name=Kabir]
RestClient post().uri(url).body(request).retrieve().toEntity(Student.class)
-> 201 CREATED /students/3 Student[id=3, name=Kabir] same result: true
RestTemplate postForLocation(url, request)
-> /students/3
RestClient post().uri(url).body(request).retrieve().toBodilessEntity().getHeaders().getLocation()
-> /students/3 same result: true
RestTemplate put(url, request, 1)
-> Asha K
RestClient put().uri(url, 1).body(request).retrieve().toBodilessEntity()
-> Asha K (status 204 NO_CONTENT) same result: true
RestTemplate delete(url, 1)
-> then GET -> 404
RestClient delete().uri(url, 1).retrieve().toBodilessEntity()
-> then GET -> 404 (delete status 204 NO_CONTENT) same result: true
RestTemplate headForHeaders(url, 1) content-type
-> application/json
RestClient head().uri(url, 1).retrieve().toBodilessEntity().getHeaders()
-> application/json same result: true
RestTemplate optionsForAllow(url)
-> [GET, HEAD, OPTIONS, POST]
RestClient options().uri(url).retrieve().toBodilessEntity().getHeaders().getAllow()
-> [GET, HEAD, OPTIONS, POST] same result: true
RestTemplate exchange(url, GET, new HttpEntity<>(headers), new ParameterizedTypeReference<List<Student>>() {})
-> [Student[id=1, name=Asha], Student[id=2, name=Ravi]]
RestClient get().uri(url).headers(h -> ...).retrieve().body(new ParameterizedTypeReference<List<Student>>() {})
-> [Student[id=1, name=Asha], Student[id=2, name=Ravi]] same result: true
server saw Authorization on both: Bearer tok-123
LegacyStudentClient.findById(1) == StudentClient.findById(1): true
LegacyStudentClient.findAll(token) == StudentClient.findAll(token): true
@@ -0,0 +1,57 @@
# 01-method-mapping (Spring Boot 4.2.0, JDK 25)
server: StudentController on http://localhost:<random port>, seeded with 1=Asha, 2=Ravi
RestTemplate getForObject(url, Student.class, 1)
-> Student[id=1, name=Asha]
RestClient get().uri(url, 1).retrieve().body(Student.class)
-> Student[id=1, name=Asha] same result: true
RestTemplate getForEntity(url, Student.class, 2)
-> 200 OK application/json Student[id=2, name=Ravi]
RestClient get().uri(url, 2).retrieve().toEntity(Student.class)
-> 200 OK application/json Student[id=2, name=Ravi] same result: true
RestTemplate postForObject(url, request, Student.class)
-> Student[id=3, name=Meera]
RestClient post().uri(url).body(request).retrieve().body(Student.class)
-> Student[id=3, name=Meera] same result: true
RestTemplate postForEntity(url, request, Student.class)
-> 201 CREATED /students/3 Student[id=3, name=Kabir]
RestClient post().uri(url).body(request).retrieve().toEntity(Student.class)
-> 201 CREATED /students/3 Student[id=3, name=Kabir] same result: true
RestTemplate postForLocation(url, request)
-> /students/3
RestClient post().uri(url).body(request).retrieve().toBodilessEntity().getHeaders().getLocation()
-> /students/3 same result: true
RestTemplate put(url, request, 1)
-> Asha K
RestClient put().uri(url, 1).body(request).retrieve().toBodilessEntity()
-> Asha K (status 204 NO_CONTENT) same result: true
RestTemplate delete(url, 1)
-> then GET -> 404
RestClient delete().uri(url, 1).retrieve().toBodilessEntity()
-> then GET -> 404 (delete status 204 NO_CONTENT) same result: true
RestTemplate headForHeaders(url, 1) content-type
-> application/json
RestClient head().uri(url, 1).retrieve().toBodilessEntity().getHeaders()
-> application/json same result: true
RestTemplate optionsForAllow(url)
-> [GET, HEAD, OPTIONS, POST]
RestClient options().uri(url).retrieve().toBodilessEntity().getHeaders().getAllow()
-> [GET, HEAD, OPTIONS, POST] same result: true
RestTemplate exchange(url, GET, new HttpEntity<>(headers), new ParameterizedTypeReference<List<Student>>() {})
-> [Student[id=1, name=Asha], Student[id=2, name=Ravi]]
RestClient get().uri(url).headers(h -> ...).retrieve().body(new ParameterizedTypeReference<List<Student>>() {})
-> [Student[id=1, name=Asha], Student[id=2, name=Ravi]] same result: true
server saw Authorization on both: Bearer tok-123
LegacyStudentClient.findById(1) == StudentClient.findById(1): true
LegacyStudentClient.findAll(token) == StudentClient.findAll(token): true
@@ -0,0 +1,17 @@
# 02-error-defaults (Spring Boot 4.1.3, JDK 25)
GET /students/99 (404)
RestTemplate : org.springframework.web.client.HttpClientErrorException$NotFound
RestClient : org.springframework.web.client.HttpClientErrorException$NotFound
RestTemplate message : 404 on GET request for "http://localhost:<port>/students/99": "{"timestamp":"<time>","status":404,"error":"Not Found","path":"/students/99"}"
RestClient message : 404 Not Found: "{"timestamp":"<time>","status":404,"error":"Not Found","path":"/students/99"}"
same message: false
GET /boom (500)
RestTemplate : org.springframework.web.client.HttpServerErrorException$InternalServerError
RestClient : org.springframework.web.client.HttpServerErrorException$InternalServerError
RestTemplate message : 500 on GET request for "http://localhost:<port>/boom": "{"timestamp":"<time>","status":500,"error":"Internal Server Error","path":"/boom"}"
RestClient message : 500 Internal Server Error: "{"timestamp":"<time>","status":500,"error":"Internal Server Error","path":"/boom"}"
same message: false
connection refused (nothing listening)
RestTemplate : org.springframework.web.client.ResourceAccessException <- cause java.net.ConnectException
RestClient : org.springframework.web.client.ResourceAccessException <- cause java.net.ConnectException
204 No Content body: RestTemplate.getForObject -> null, RestClient.body(String.class) -> null
@@ -0,0 +1,17 @@
# 02-error-defaults (Spring Boot 4.2.0, JDK 25)
GET /students/99 (404)
RestTemplate : org.springframework.web.client.HttpClientErrorException$NotFound
RestClient : org.springframework.web.client.HttpClientErrorException$NotFound
RestTemplate message : 404 on GET request for "http://localhost:<port>/students/99": "{"timestamp":"<time>","status":404,"error":"Not Found","path":"/students/99"}"
RestClient message : 404 Not Found: "{"timestamp":"<time>","status":404,"error":"Not Found","path":"/students/99"}"
same message: false
GET /boom (500)
RestTemplate : org.springframework.web.client.HttpServerErrorException$InternalServerError
RestClient : org.springframework.web.client.HttpServerErrorException$InternalServerError
RestTemplate message : 500 on GET request for "http://localhost:<port>/boom": "{"timestamp":"<time>","status":500,"error":"Internal Server Error","path":"/boom"}"
RestClient message : 500 Internal Server Error: "{"timestamp":"<time>","status":500,"error":"Internal Server Error","path":"/boom"}"
same message: false
connection refused (nothing listening)
RestTemplate : org.springframework.web.client.ResourceAccessException <- cause java.net.ConnectException
RestClient : org.springframework.web.client.ResourceAccessException <- cause java.net.ConnectException
204 No Content body: RestTemplate.getForObject -> null, RestClient.body(String.class) -> null
@@ -0,0 +1,10 @@
# 03-error-handler-migration (Spring Boot 4.1.3, JDK 25)
GET /students/99 with a custom 404 translation
RestTemplate.setErrorHandler(handler) -> StudentNotFoundException: no such resource: /students/99
builder.defaultStatusHandler(<same handler>) -> StudentNotFoundException: no such resource: /students/99
builder.defaultStatusHandler(predicate, lambda) -> StudentNotFoundException: no such resource: /students/99
retrieve().onStatus(predicate, lambda) per call -> StudentNotFoundException: no such resource: /students/99
GET /boom (500), not claimed by the custom handler
RestTemplate -> org.springframework.web.client.HttpServerErrorException$InternalServerError
defaultStatusHandler(<handler>) -> org.springframework.web.client.HttpServerErrorException$InternalServerError
defaultStatusHandler(pred, lambda)-> org.springframework.web.client.HttpServerErrorException$InternalServerError
@@ -0,0 +1,10 @@
# 03-error-handler-migration (Spring Boot 4.2.0, JDK 25)
GET /students/99 with a custom 404 translation
RestTemplate.setErrorHandler(handler) -> StudentNotFoundException: no such resource: /students/99
builder.defaultStatusHandler(<same handler>) -> StudentNotFoundException: no such resource: /students/99
builder.defaultStatusHandler(predicate, lambda) -> StudentNotFoundException: no such resource: /students/99
retrieve().onStatus(predicate, lambda) per call -> StudentNotFoundException: no such resource: /students/99
GET /boom (500), not claimed by the custom handler
RestTemplate -> org.springframework.web.client.HttpServerErrorException$InternalServerError
defaultStatusHandler(<handler>) -> org.springframework.web.client.HttpServerErrorException$InternalServerError
defaultStatusHandler(pred, lambda)-> org.springframework.web.client.HttpServerErrorException$InternalServerError
@@ -0,0 +1,7 @@
# 04-exchange-trap (Spring Boot 4.1.3, JDK 25)
RestTemplate.exchange(GET /students/99) -> throws NotFound
RestClient.get()...retrieve().body(...) -> throws NotFound
RestClient.get()...exchange((req, res) -> res.bodyTo(Student.class))
-> throws: nothing; returned Student[id=null, name=null]
RestClient.get()...exchange(...) on GET /boom -> no exception; handler saw 500 INTERNAL_SERVER_ERROR {"timestamp":"<time>","status":500,"error":"Internal Server Error","path":"/boom"}
exchange(...) with an explicit isError() check -> IllegalStateException: HTTP 404 for /students/99
@@ -0,0 +1,7 @@
# 04-exchange-trap (Spring Boot 4.2.0, JDK 25)
RestTemplate.exchange(GET /students/99) -> throws NotFound
RestClient.get()...retrieve().body(...) -> throws NotFound
RestClient.get()...exchange((req, res) -> res.bodyTo(Student.class))
-> throws: nothing; returned Student[id=null, name=null]
RestClient.get()...exchange(...) on GET /boom -> no exception; handler saw 500 INTERNAL_SERVER_ERROR {"timestamp":"<time>","status":500,"error":"Internal Server Error","path":"/boom"}
exchange(...) with an explicit isError() check -> IllegalStateException: HTTP 404 for /students/99
@@ -0,0 +1,6 @@
# 05-bridge-what-is-copied (Spring Boot 4.1.3, JDK 25)
GET /whoami, what the server received
RestTemplate(JdkClientHttpRequestFactory + interceptor): x-request-id=abc-123 user-agent=Java-http-client/25.0.5.1
RestClient.create(thatTemplate) : x-request-id=abc-123 user-agent=Java-http-client/25.0.5.1
RestClient.create() (no bridge) : x-request-id=null user-agent=Java-http-client/25.0.5.1
GET /students/99 through the bridge, template had a custom ResponseErrorHandler -> StudentNotFoundException
@@ -0,0 +1,6 @@
# 05-bridge-what-is-copied (Spring Boot 4.2.0, JDK 25)
GET /whoami, what the server received
RestTemplate(JdkClientHttpRequestFactory + interceptor): x-request-id=abc-123 user-agent=Java-http-client/25.0.5.1
RestClient.create(thatTemplate) : x-request-id=abc-123 user-agent=Java-http-client/25.0.5.1
RestClient.create() (no bridge) : x-request-id=null user-agent=Java-http-client/25.0.5.1
GET /students/99 through the bridge, template had a custom ResponseErrorHandler -> StudentNotFoundException
@@ -0,0 +1,9 @@
# 06-bridge-uri-encoding (Spring Boot 4.1.3, JDK 25)
RestTemplate default URI encoding mode : URI_COMPONENT
RestClient default URI encoding mode : TEMPLATE_AND_VALUES (DefaultUriBuilderFactory default)
variable q = "C++", template "/search?q={q}"
new RestTemplate() wire: q=C++ server decoded q = "C "
RestClient.create(restTemplate) wire: q=C%2B%2B server decoded q = "C++"
RestClient.create() wire: q=C%2B%2B server decoded q = "C++"
builder(rt).uriBuilderFactory(URI_COMPONENT) wire: q=C++ server decoded q = "C "
@@ -0,0 +1,9 @@
# 06-bridge-uri-encoding (Spring Boot 4.2.0, JDK 25)
RestTemplate default URI encoding mode : URI_COMPONENT
RestClient default URI encoding mode : TEMPLATE_AND_VALUES (DefaultUriBuilderFactory default)
variable q = "C++", template "/search?q={q}"
new RestTemplate() wire: q=C++ server decoded q = "C "
RestClient.create(restTemplate) wire: q=C%2B%2B server decoded q = "C++"
RestClient.create() wire: q=C%2B%2B server decoded q = "C++"
builder(rt).uriBuilderFactory(URI_COMPONENT) wire: q=C++ server decoded q = "C "
@@ -0,0 +1,14 @@
# 07-default-request-factories (Spring Boot 4.1.3, JDK 25)
request factory class on RestTemplate: new RestTemplate() -> org.springframework.http.client.SimpleClientHttpRequestFactory
request factory class on RestTemplate: RestTemplateBuilder.build() -> org.springframework.http.client.JdkClientHttpRequestFactory
User-Agent the server received (GET /whoami)
new RestTemplate() : Java/25.0.5.1
RestClient.create() : Java-http-client/25.0.5.1
injected RestClient.Builder (Boot) : Java-http-client/25.0.5.1
RestTemplateBuilder.build() (Boot) : Java-http-client/25.0.5.1
PATCH /students/1
new RestTemplate().patchForObject(...) -> ResourceAccessException: I/O error on PATCH request for "http://localhost:<port>/students/1": Invalid HTTP method: PATCH
RestClient.create().patch()...body(Student) -> Student[id=1, name=Asha P]
new RestTemplate(new JdkClientHttpRequestFactory()).patchForObject(...) -> Student[id=1, name=Asha Q]
@@ -0,0 +1,14 @@
# 07-default-request-factories (Spring Boot 4.2.0, JDK 25)
request factory class on RestTemplate: new RestTemplate() -> org.springframework.http.client.SimpleClientHttpRequestFactory
request factory class on RestTemplate: RestTemplateBuilder.build() -> org.springframework.http.client.JdkClientHttpRequestFactory
User-Agent the server received (GET /whoami)
new RestTemplate() : Java/25.0.5.1
RestClient.create() : Java-http-client/25.0.5.1
injected RestClient.Builder (Boot) : Java-http-client/25.0.5.1
RestTemplateBuilder.build() (Boot) : Java-http-client/25.0.5.1
PATCH /students/1
new RestTemplate().patchForObject(...) -> ResourceAccessException: I/O error on PATCH request for "http://localhost:<port>/students/1": Invalid HTTP method: PATCH
RestClient.create().patch()...body(Student) -> Student[id=1, name=Asha P]
new RestTemplate(new JdkClientHttpRequestFactory()).patchForObject(...) -> Student[id=1, name=Asha Q]
@@ -0,0 +1,7 @@
# 08-interceptor-reads-body (Spring Boot 4.1.3, JDK 25)
GET /text (server body: "plain text body"); the interceptor reads the body to log it
RestTemplate, default factory -> caller got null
RestTemplate + BufferingClientHttpRequestFactory -> caller got "plain text body"
RestClient, interceptor only -> caller got null
RestClient + bufferContent((uri, method) -> true) -> caller got "plain text body"
interceptor logged: [plain text body, plain text body, plain text body, plain text body]
@@ -0,0 +1,7 @@
# 08-interceptor-reads-body (Spring Boot 4.2.0, JDK 25)
GET /text (server body: "plain text body"); the interceptor reads the body to log it
RestTemplate, default factory -> caller got null
RestTemplate + BufferingClientHttpRequestFactory -> caller got "plain text body"
RestClient, interceptor only -> caller got null
RestClient + bufferContent((uri, method) -> true) -> caller got "plain text body"
interceptor logged: [plain text body, plain text body, plain text body, plain text body]
@@ -0,0 +1,8 @@
# 09-timeouts (Spring Boot 4.1.3, JDK 25)
server: GET /slow?ms=1500 sleeps 1500 ms
application.properties equivalent: spring.http.clients.connect-timeout=300ms, spring.http.clients.read-timeout=300ms
injected RestClient.Builder (Boot properties) -> ResourceAccessException <- java.net.http.HttpTimeoutException, gave up after roughly 300-1200 ms
RestTemplateBuilder.build() (same Boot properties) -> ResourceAccessException <- java.net.http.HttpTimeoutException, gave up after roughly 300-1200 ms
RestClient.builder().requestFactory(detect().build(HttpClientSettings.defaults().withReadTimeout(300ms))) -> ResourceAccessException <- java.net.http.HttpTimeoutException, gave up after roughly 300-1200 ms
RestClient.create() (no timeouts configured) -> "done after 1500 ms", >1200 ms
@@ -0,0 +1,8 @@
# 09-timeouts (Spring Boot 4.2.0, JDK 25)
server: GET /slow?ms=1500 sleeps 1500 ms
application.properties equivalent: spring.http.clients.connect-timeout=300ms, spring.http.clients.read-timeout=300ms
injected RestClient.Builder (Boot properties) -> ResourceAccessException <- java.net.http.HttpTimeoutException, gave up after roughly 300-1200 ms
RestTemplateBuilder.build() (same Boot properties) -> ResourceAccessException <- java.net.http.HttpTimeoutException, gave up after roughly 300-1200 ms
RestClient.builder().requestFactory(detect().build(HttpClientSettings.defaults().withReadTimeout(300ms))) -> ResourceAccessException <- java.net.http.HttpTimeoutException, gave up after roughly 300-1200 ms
RestClient.create() (no timeouts configured) -> "done after 1500 ms", >1200 ms
@@ -0,0 +1,9 @@
# 10-test-clients (Spring Boot 4.1.3, JDK 25)
TestRestTemplate.getForEntity("/students/1", Student.class) -> 200 OK Student[id=1, name=Asha]
RestTestClient.get().uri("/students/1").exchange().expectStatus().isOk().expectBody(Student.class) -> Student[id=1, name=Asha]
TestRestTemplate on a 404 does not throw: status 404 NOT_FOUND
RestTestClient on a 404 does not throw: expectStatus().isNotFound() passed
TestRestTemplate.postForEntity(...) -> 201 CREATED Location /students/3
RestTestClient.post()...body(...).exchange().expectStatus().isCreated().expectHeader().exists("Location") passed
TestRestTemplate.withBasicAuth("user", "pw") -> server saw Authorization: Basic dXNlcjpwdw==
RestTestClient.mutate().defaultHeaders(h -> h.setBasicAuth("user", "pw")) -> server saw Authorization: Basic dXNlcjpwdw==
@@ -0,0 +1,9 @@
# 10-test-clients (Spring Boot 4.2.0, JDK 25)
TestRestTemplate.getForEntity("/students/1", Student.class) -> 200 OK Student[id=1, name=Asha]
RestTestClient.get().uri("/students/1").exchange().expectStatus().isOk().expectBody(Student.class) -> Student[id=1, name=Asha]
TestRestTemplate on a 404 does not throw: status 404 NOT_FOUND
RestTestClient on a 404 does not throw: expectStatus().isNotFound() passed
TestRestTemplate.postForEntity(...) -> 201 CREATED Location /students/3
RestTestClient.post()...body(...).exchange().expectStatus().isCreated().expectHeader().exists("Location") passed
TestRestTemplate.withBasicAuth("user", "pw") -> server saw Authorization: Basic dXNlcjpwdw==
RestTestClient.mutate().defaultHeaders(h -> h.setBasicAuth("user", "pw")) -> server saw Authorization: Basic dXNlcjpwdw==
@@ -0,0 +1,3 @@
# 11-mock-server (Spring Boot 4.1.3, JDK 25)
MockRestServiceServer.bindTo(restTemplate) -> Student[id=1, name=Asha]
MockRestServiceServer.bindTo(restClientBuilder) -> Student[id=1, name=Asha]
@@ -0,0 +1,3 @@
# 11-mock-server (Spring Boot 4.2.0, JDK 25)
MockRestServiceServer.bindTo(restTemplate) -> Student[id=1, name=Asha]
MockRestServiceServer.bindTo(restClientBuilder) -> Student[id=1, name=Asha]
@@ -0,0 +1,5 @@
# 12-auto-configured-beans (Spring Boot 4.1.3, JDK 25)
RestClient.Builder beans : 1
RestTemplateBuilder beans: 1
RestTemplate beans : 0 (Boot never registers a RestTemplate itself)
two getBean(RestClient.Builder) calls return the same instance: false (prototype scope: configure your copy freely)
@@ -0,0 +1,5 @@
# 12-auto-configured-beans (Spring Boot 4.2.0, JDK 25)
RestClient.Builder beans : 1
RestTemplateBuilder beans: 1
RestTemplate beans : 0 (Boot never registers a RestTemplate itself)
two getBean(RestClient.Builder) calls return the same instance: false (prototype scope: configure your copy freely)
@@ -0,0 +1,3 @@
# 13-resttemplate-compiler-warnings (Spring Boot 4.1.3, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/UsesRestTemplate.java
exit: 0
@@ -0,0 +1,10 @@
# 13-resttemplate-compiler-warnings (Spring Boot 4.2.0, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/UsesRestTemplate.java
src/broken/UsesRestTemplate.java:11: warning: [removal] RestTemplateBuilder in org.springframework.boot.restclient has been deprecated and marked for removal
public String fetch(RestTemplateBuilder builder) {
^
src/broken/UsesRestTemplate.java:12: warning: [removal] RestTemplate in org.springframework.web.client has been deprecated and marked for removal
RestTemplate rest = builder.build();
^
2 warnings
exit: 0
@@ -0,0 +1,3 @@
# 14-testresttemplate-compiler-warnings (Spring Boot 4.1.3, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/UsesTestRestTemplate.java
exit: 0
@@ -0,0 +1,7 @@
# 14-testresttemplate-compiler-warnings (Spring Boot 4.2.0, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/UsesTestRestTemplate.java
src/broken/UsesTestRestTemplate.java:8: warning: [removal] TestRestTemplate in org.springframework.boot.resttestclient has been deprecated and marked for removal
public String fetch(TestRestTemplate rest) {
^
1 warning
exit: 0
@@ -0,0 +1,19 @@
# 15-old-timeout-settings-compiler-error (Spring Boot 4.1.3, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/OldTimeoutSettings.java
src/broken/OldTimeoutSettings.java:4: error: cannot find symbol
import org.springframework.boot.http.client.ClientHttpRequestFactorySettings;
^
symbol: class ClientHttpRequestFactorySettings
location: package org.springframework.boot.http.client
src/broken/OldTimeoutSettings.java:14: error: cannot find symbol
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
^
symbol: class ClientHttpRequestFactorySettings
location: class OldTimeoutSettings
src/broken/OldTimeoutSettings.java:14: error: cannot find symbol
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
^
symbol: variable ClientHttpRequestFactorySettings
location: class OldTimeoutSettings
3 errors
exit: 1
@@ -0,0 +1,19 @@
# 15-old-timeout-settings-compiler-error (Spring Boot 4.2.0, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/OldTimeoutSettings.java
src/broken/OldTimeoutSettings.java:4: error: cannot find symbol
import org.springframework.boot.http.client.ClientHttpRequestFactorySettings;
^
symbol: class ClientHttpRequestFactorySettings
location: package org.springframework.boot.http.client
src/broken/OldTimeoutSettings.java:14: error: cannot find symbol
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
^
symbol: class ClientHttpRequestFactorySettings
location: class OldTimeoutSettings
src/broken/OldTimeoutSettings.java:14: error: cannot find symbol
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
^
symbol: variable ClientHttpRequestFactorySettings
location: class OldTimeoutSettings
3 errors
exit: 1
@@ -0,0 +1,3 @@
# 16-new-timeout-settings-compiler (Spring Boot 4.1.3, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/NewTimeoutSettings.java
exit: 0
@@ -0,0 +1,3 @@
# 16-new-timeout-settings-compiler (Spring Boot 4.2.0, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/broken/NewTimeoutSettings.java
exit: 0
@@ -0,0 +1,3 @@
# 17-migrated-client-compiler (Spring Boot 4.1.3, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/main/java/com/ankurm/rtmigration/StudentClient.java
exit: 0
@@ -0,0 +1,3 @@
# 17-migrated-client-compiler (Spring Boot 4.2.0, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken src/main/java/com/ankurm/rtmigration/StudentClient.java
exit: 0
@@ -0,0 +1,3 @@
# 18-legacy-client-without-suppression (Spring Boot 4.1.3, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken target/LegacyStudentClient.java
exit: 0
@@ -0,0 +1,10 @@
# 18-legacy-client-without-suppression (Spring Boot 4.2.0, JDK 25.0.5.1)
$ javac -Xlint:deprecation -cp <module classpath> -d target/broken target/LegacyStudentClient.java
target/LegacyStudentClient.java:19: warning: [removal] RestTemplate in org.springframework.web.client has been deprecated and marked for removal
private final RestTemplate restTemplate;
^
target/LegacyStudentClient.java:23: warning: [removal] RestTemplate in org.springframework.web.client has been deprecated and marked for removal
public LegacyStudentClient(RestTemplate restTemplate, String base) {
^
2 warnings
exit: 0
@@ -0,0 +1,25 @@
# 19-deprecation-annotations (javap -v on the published jars, JDK 25.0.5.1)
spring-web 7.0.11 org.springframework.web.client.RestTemplate : not deprecated
spring-web 7.0.11 org.springframework.web.client.RestClient : not deprecated
spring-web 7.1.0 org.springframework.web.client.RestTemplate : since="7.1" forRemoval=true
spring-web 7.1.0 org.springframework.web.client.RestClient : not deprecated
spring-boot-restclient 4.1.3 RestTemplateBuilder : not deprecated
spring-boot-restclient 4.1.3 RestTemplateCustomizer : not deprecated
spring-boot-restclient 4.1.3 RestClientCustomizer : not deprecated
spring-boot-restclient 4.1.3 autoconfigure.RestTemplateAutoConfiguration : not deprecated
spring-boot-restclient 4.1.3 autoconfigure.RestClientAutoConfiguration : not deprecated
spring-boot-resttestclient 4.1.3 TestRestTemplate : not deprecated
spring-boot-resttestclient 4.1.3 autoconfigure.AutoConfigureTestRestTemplate : not deprecated
spring-boot-resttestclient 4.1.3 autoconfigure.AutoConfigureRestTestClient : not deprecated
spring-boot-restclient 4.2.0 RestTemplateBuilder : since="4.2.0" forRemoval=true
spring-boot-restclient 4.2.0 RestTemplateCustomizer : since="4.2.0" forRemoval=true
spring-boot-restclient 4.2.0 RestClientCustomizer : not deprecated
spring-boot-restclient 4.2.0 autoconfigure.RestTemplateAutoConfiguration : since="4.2.0" forRemoval=true
spring-boot-restclient 4.2.0 autoconfigure.RestClientAutoConfiguration : not deprecated
spring-boot-resttestclient 4.2.0 TestRestTemplate : since="4.2.0" forRemoval=true
spring-boot-resttestclient 4.2.0 autoconfigure.AutoConfigureTestRestTemplate : since="4.2.0" forRemoval=true
spring-boot-resttestclient 4.2.0 autoconfigure.AutoConfigureRestTestClient : not deprecated
@@ -0,0 +1,23 @@
# 20-openrewrite-diff (io.moderne.recipe:rewrite-spring 0.40.1, rewrite-maven-plugin 6.46.1, Spring Boot 4.2.0)
$ mvn rewrite:run -Drewrite.activeRecipes=io.moderne.java.spring.boot3.MigrateRestTemplateToRestClient
@@ -12 +12 @@ import org.springframework.http.ResponseEntity;
-import org.springframework.web.client.RestTemplate;
+import org.springframework.web.client.RestClient;
@@ -20 +20 @@ public class RemoteClient {
- private final RestTemplate restTemplate = new RestTemplate();
+ private final RestClient restTemplate = RestClient.create();
@@ -29 +29 @@ public class RemoteClient {
- return this.restTemplate.getForObject(this.base + "/students/{id}", Student.class, id);
+ return this.restTemplate.get().uri(this.base + "/students/{id}", id).retrieve().body(Student.class);
@@ -33 +33 @@ public class RemoteClient {
- return this.restTemplate.postForEntity(this.base + "/students", s, Student.class);
+ return this.restTemplate.post().uri(this.base + "/students").body(s).retrieve().toEntity(Student.class);
@@ -37 +37 @@ public class RemoteClient {
- this.restTemplate.delete(this.base + "/students/{id}", id);
+ this.restTemplate.delete().uri(this.base + "/students/{id}", id).retrieve().toBodilessEntity();
@@ -43,3 +43,2 @@ public class RemoteClient {
- return this.restTemplate.exchange(this.base + "/students", HttpMethod.GET, new HttpEntity<>(headers),
- new ParameterizedTypeReference<List<Student>>() {
- }).getBody();
+ return this.restTemplate.method(HttpMethod.GET).uri(this.base + "/students").headers(h -> h.addAll(new HttpEntity<>(headers).getHeaders())).body(new HttpEntity<>(headers).getBody()).retrieve().toEntity(new ParameterizedTypeReference<List<Student>>() {
+ }).getBody();
@@ -0,0 +1,5 @@
# 21-openrewrite-generated-client-run (Spring Boot 4.1.3, JDK 25)
find(1) -> Student[id=1, name=Asha]
create(Meera) -> 201 CREATED
remove(1) -> ok
all("tok") -> THROWS java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "body" is null
@@ -0,0 +1,5 @@
# 21-openrewrite-generated-client-run (Spring Boot 4.2.0, JDK 25)
find(1) -> Student[id=1, name=Asha]
create(Meera) -> 201 CREATED
remove(1) -> ok
all("tok") -> THROWS java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "body" is null
@@ -0,0 +1,2 @@
# 22-configured-client (Spring Boot 4.1.3, JDK 25)
RestClientConfig.apiClient GET /whoami -> server saw x-request-id: <36-character UUID>
@@ -0,0 +1,2 @@
# 22-configured-client (Spring Boot 4.2.0, JDK 25)
RestClientConfig.apiClient GET /whoami -> server saw x-request-id: <36-character UUID>
@@ -0,0 +1,13 @@
# 23-http-client-properties (spring-configuration-metadata.json, spring-boot-http-client jars)
Spring Boot 4.1.3
spring.http.clients.connect-timeout current
spring.http.clients.read-timeout current
spring.http.client.connect-timeout DEPRECATED -> spring.http.clients.connect-timeout
spring.http.client.read-timeout DEPRECATED -> spring.http.clients.read-timeout
Spring Boot 4.2.0
spring.http.clients.connect-timeout current
spring.http.clients.read-timeout current
spring.http.client.connect-timeout DEPRECATED -> spring.http.clients.connect-timeout
spring.http.client.read-timeout DEPRECATED -> spring.http.clients.read-timeout
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.3</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>resttemplate-to-restclient</artifactId>
<version>1.0.0</version>
<name>resttemplate-to-restclient</name>
<description>RestTemplate to RestClient (and TestRestTemplate to RestTestClient) on Spring Framework 7.1 / Spring Boot 4.2, each claim run</description>
<properties>
<java.version>25</java.version>
<boot.label>4.1.3</boot.label>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-resttestclient</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<boot.label>${boot.label}</boot.label>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>resttemplate-to-restclient</artifactId>
<version>1.0.0</version>
<name>resttemplate-to-restclient</name>
<description>RestTemplate to RestClient (and TestRestTemplate to RestTestClient) on Spring Framework 7.1 / Spring Boot 4.2, each claim run</description>
<properties>
<java.version>25</java.version>
<boot.label>4.2.0</boot.label>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-resttestclient</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<boot.label>${boot.label}</boot.label>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Compiles each file in src/broken/ with -Xlint:deprecation against the module classpath of the
# given pom (default pom.xml = 4.2.0; pass pom-41.xml for the 4.1.3 baseline) and stores the
# compiler's own messages in output/NN-... (suffix -on-4.1.3 for the baseline).
set -u
cd "$(dirname "$0")/.."
POM="${1:-pom.xml}"
LABEL=$(grep -m1 '<boot.label>' "$POM" | sed -E 's/.*<boot.label>(.*)<\/boot.label>.*/\1/')
SUFFIX=""; [[ "$LABEL" == 4.2* ]] || SUFFIX="-on-$LABEL"
mvn -B -q -f "$POM" dependency:build-classpath -Dmdep.outputFile=target/cp.txt >/dev/null 2>&1
CP="$(cat target/cp.txt):target/classes"
compile_one() { # <source> <outfile-base>
local src="$1" base="$2" out="output/$2$SUFFIX.txt"
rm -rf target/broken && mkdir -p target/broken
{
echo "# $base (Spring Boot $LABEL, JDK $(javac -version 2>&1 | grep -v Picked | awk '{print $2}'))"
echo "\$ javac -Xlint:deprecation -cp <module classpath> -d target/broken $src"
javac -Xlint:deprecation -cp "$CP" -d target/broken "$src" 2>&1 | grep -v '^Picked up' | sed -e "s#^$(pwd)/##"
echo "exit: ${PIPESTATUS[0]}"
} > "$out"
cat "$out"
}
compile_one src/broken/UsesRestTemplate.java 13-resttemplate-compiler-warnings
compile_one src/broken/UsesTestRestTemplate.java 14-testresttemplate-compiler-warnings
compile_one src/broken/OldTimeoutSettings.java 15-old-timeout-settings-compiler-error
compile_one src/broken/NewTimeoutSettings.java 16-new-timeout-settings-compiler
# The migrated client must compile with no [removal] warning at all.
compile_one src/main/java/com/ankurm/rtmigration/StudentClient.java 17-migrated-client-compiler
# The legacy client carries @SuppressWarnings("removal"); without it the warnings come back.
sed 's/^@SuppressWarnings("removal")//' src/main/java/com/ankurm/rtmigration/LegacyStudentClient.java > target/LegacyStudentClient.java
compile_one target/LegacyStudentClient.java 18-legacy-client-without-suppression
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Runs the Moderne recipe io.moderne.java.spring.boot3.MigrateRestTemplateToRestClient
# (io.moderne.recipe:rewrite-spring 0.40.1, plugin rewrite-maven-plugin 6.46.1) on
# src/recipe/before/RemoteClient.java in a scratch project OUTSIDE this checkout (OpenRewrite
# silently skips git-ignored sources), stores the diff in output/20-openrewrite-diff.txt and
# copies the generated class to src/test/.../recipe/RemoteClient.java, where RecipeOutputTest runs it.
set -euo pipefail
cd "$(dirname "$0")/.."
HERE=$(pwd)
W=$(mktemp -d)
mkdir -p "$W/src/main/java/com/ankurm/rtmigration/recipe"
cat > "$W/pom.xml" <<'P'
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.2.0</version><relativePath/></parent>
<groupId>demo</groupId><artifactId>orw</artifactId><version>1.0.0</version>
<properties><java.version>25</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webmvc</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-restclient</artifactId></dependency>
</dependencies>
</project>
P
cp src/main/java/com/ankurm/rtmigration/Student.java "$W/src/main/java/com/ankurm/rtmigration/" 2>/dev/null || { mkdir -p "$W/src/main/java/com/ankurm/rtmigration"; cp src/main/java/com/ankurm/rtmigration/Student.java "$W/src/main/java/com/ankurm/rtmigration/"; }
cp src/recipe/before/RemoteClient.java "$W/src/main/java/com/ankurm/rtmigration/recipe/"
( cd "$W" && git init -q . && git add -A && git -c user.email=a@b -c user.name=n commit -qm before
mvn -B -q org.openrewrite.maven:rewrite-maven-plugin:6.46.1:run \
-Drewrite.recipeArtifactCoordinates=io.moderne.recipe:rewrite-spring:0.40.1 \
-Drewrite.activeRecipes=io.moderne.java.spring.boot3.MigrateRestTemplateToRestClient 2>&1 | { grep -v -E '^Picked|^WARNING' || true; } | tail -5
{ echo "# 20-openrewrite-diff (io.moderne.recipe:rewrite-spring 0.40.1, rewrite-maven-plugin 6.46.1, Spring Boot 4.2.0)"
echo "\$ mvn rewrite:run -Drewrite.activeRecipes=io.moderne.java.spring.boot3.MigrateRestTemplateToRestClient"
git diff -U0 | grep -v -E '^(diff|index|---|\+\+\+)'; } > "$HERE/output/20-openrewrite-diff.txt" )
cp "$W/src/main/java/com/ankurm/rtmigration/recipe/RemoteClient.java" src/test/java/com/ankurm/rtmigration/recipe/RemoteClient.java
rm -rf "$W"
cat output/20-openrewrite-diff.txt
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
# Reads the deprecation annotations straight out of the published jars: which types carry
# @Deprecated(since, forRemoval) in Spring Framework 7.0.x vs 7.1.0 and Spring Boot 4.1.3 vs 4.2.0.
# Needs the jars in ~/.m2 (run `mvn test` and `mvn -f pom-41.xml test` once first).
set -u
cd "$(dirname "$0")/.."
M="$HOME/.m2/repository/org/springframework"
OUT=output/19-deprecation-annotations.txt
FW41=$(ls "$M/spring-web" | grep -E '^7\.0\.' | sort -V | tail -1)
annot() { # <jar> <class> -> "since=X forRemoval=true" or "not deprecated"
local out
out=$(javap -v -cp "$1" "$2" 2>/dev/null | awk '/^RuntimeVisibleAnnotations:/{f=1} f&&/java.lang.Deprecated\(/{d=1} d&&/since=/{s=$0} d&&/forRemoval=/{r=$0} /^[A-Za-z]/&&!/^RuntimeVisibleAnnotations/&&f&&!/^ /{} END{ if(d) print s " " r }' | tr -s " " | sed "s/^ //")
[ -n "$out" ] && echo "$out" || echo "not deprecated"
}
{
echo "# 19-deprecation-annotations (javap -v on the published jars, JDK $(javac -version 2>&1 | grep -v Picked | awk '{print $2}'))"
echo
for fw in "$FW41" 7.1.0; do
jar="$M/spring-web/$fw/spring-web-$fw.jar"
echo "spring-web $fw org.springframework.web.client.RestTemplate : $(annot "$jar" org.springframework.web.client.RestTemplate)"
echo "spring-web $fw org.springframework.web.client.RestClient : $(annot "$jar" org.springframework.web.client.RestClient)"
done
echo
for b in 4.1.3 4.2.0; do
rj="$HOME/.m2/repository/org/springframework/boot/spring-boot-restclient/$b/spring-boot-restclient-$b.jar"
tj="$HOME/.m2/repository/org/springframework/boot/spring-boot-resttestclient/$b/spring-boot-resttestclient-$b.jar"
for c in org.springframework.boot.restclient.RestTemplateBuilder org.springframework.boot.restclient.RestTemplateCustomizer \
org.springframework.boot.restclient.RestClientCustomizer org.springframework.boot.restclient.autoconfigure.RestTemplateAutoConfiguration \
org.springframework.boot.restclient.autoconfigure.RestClientAutoConfiguration; do
echo "spring-boot-restclient $b ${c#org.springframework.boot.restclient.} : $(annot "$rj" "$c")"
done
for c in org.springframework.boot.resttestclient.TestRestTemplate org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate \
org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient; do
echo "spring-boot-resttestclient $b ${c#org.springframework.boot.resttestclient.} : $(annot "$tj" "$c")"
done
echo
done
} | sed "s#$HOME#~#g" > "$OUT"
cat "$OUT"
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Reads the HTTP-client properties from spring-configuration-metadata.json inside the published
# spring-boot-http-client jars: the plural spring.http.clients.* keys and the deprecated singular ones.
set -u
cd "$(dirname "$0")/.."
OUT=output/23-http-client-properties.txt
{
echo "# 23-http-client-properties (spring-configuration-metadata.json, spring-boot-http-client jars)"
for v in 4.1.3 4.2.0; do
echo
echo "Spring Boot $v"
unzip -p "$HOME/.m2/repository/org/springframework/boot/spring-boot-http-client/$v/spring-boot-http-client-$v.jar" META-INF/spring-configuration-metadata.json \
| python3 -c "
import json,sys
for p in json.load(sys.stdin)['properties']:
n=p['name']
if n in ('spring.http.clients.connect-timeout','spring.http.clients.read-timeout','spring.http.client.connect-timeout','spring.http.client.read-timeout'):
d=p.get('deprecation')
print(' %-40s %s' % (n, 'DEPRECATED' + (' -> ' + d['replacement'] if d and 'replacement' in d else '') if d else 'current'))
"
done
} > "$OUT"
cat "$OUT"
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# Regenerates every file in output/ on Spring Boot 4.2.0 (GA) and on the 4.1.3 baseline.
# Needs JDK 25 and Maven 3.9 on PATH, plus network access to Maven Central.
# scripts/openrewrite.sh downloads the Moderne recipe artifact; it is the only step that
# needs more than the jars the module already depends on.
set -euo pipefail
cd "$(dirname "$0")/.."
scripts/openrewrite.sh >/dev/null
mvn -B -q test
mvn -B -q -f pom-41.xml test
scripts/compile-broken.sh pom.xml >/dev/null
scripts/compile-broken.sh pom-41.xml >/dev/null
scripts/probe-jars.sh >/dev/null
scripts/probe-properties.sh >/dev/null
echo "done: $(ls output | wc -l) files in output/"
@@ -0,0 +1,19 @@
import java.time.Duration;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.boot.http.client.HttpClientSettings;
import org.springframework.web.client.RestClient;
/**
* Not part of the build; the corrected form of OldTimeoutSettings. Compiled by the same script
* so the before and after are two compiler results rather than a claim.
*/
public class NewTimeoutSettings {
public RestClient build(RestClient.Builder builder) {
HttpClientSettings settings = HttpClientSettings.defaults()
.withConnectTimeout(Duration.ofSeconds(2))
.withReadTimeout(Duration.ofSeconds(5));
return builder.requestFactory(ClientHttpRequestFactoryBuilder.detect().build(settings)).build();
}
}
@@ -0,0 +1,19 @@
import java.time.Duration;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.boot.http.client.ClientHttpRequestFactorySettings;
import org.springframework.web.client.RestClient;
/**
* Not part of the build. The timeout snippet the previous version of the article carried:
* the settings type it names no longer exists.
*/
public class OldTimeoutSettings {
public RestClient build(RestClient.Builder builder) {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
.withConnectTimeout(Duration.ofSeconds(2))
.withReadTimeout(Duration.ofSeconds(5));
return builder.requestFactory(ClientHttpRequestFactoryBuilder.detect().build(settings)).build();
}
}
@@ -0,0 +1,15 @@
import org.springframework.web.client.RestTemplate;
import org.springframework.boot.restclient.RestTemplateBuilder;
/**
* Not part of the build. scripts/compile-broken.sh compiles it with -Xlint:deprecation and
* commits the compiler's own message. RestTemplate and the Boot builder around it are
* deprecated for removal in Spring Framework 7.1 / Spring Boot 4.2.
*/
public class UsesRestTemplate {
public String fetch(RestTemplateBuilder builder) {
RestTemplate rest = builder.build();
return rest.getForObject("http://localhost:8080/ping", String.class);
}
}
@@ -0,0 +1,11 @@
import org.springframework.boot.resttestclient.TestRestTemplate;
/**
* Not part of the build. TestRestTemplate is deprecated for removal since Spring Boot 4.2.0.
*/
public class UsesTestRestTemplate {
public String fetch(TestRestTemplate rest) {
return rest.getForObject("/ping", String.class);
}
}
@@ -0,0 +1,39 @@
package com.ankurm.rtmigration;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
/**
* The "before": a typical RestTemplate client. On Spring Framework 7.1 / Boot 4.2 every
* reference to RestTemplate is a [removal] warning, which is why the whole class carries the
* suppression: it is kept only so the tests can run old and new side by side.
*/
@SuppressWarnings("removal")
public class LegacyStudentClient {
private final RestTemplate restTemplate;
private final String base;
public LegacyStudentClient(RestTemplate restTemplate, String base) {
this.restTemplate = restTemplate;
this.base = base;
}
public Student findById(int id) {
return this.restTemplate.getForObject(this.base + "/students/{id}", Student.class, id);
}
public List<Student> findAll(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
return this.restTemplate.exchange(this.base + "/students", HttpMethod.GET, new HttpEntity<>(headers),
new ParameterizedTypeReference<List<Student>>() {
}).getBody();
}
}
@@ -0,0 +1,34 @@
package com.ankurm.rtmigration;
import java.time.Duration;
import java.util.UUID;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.boot.http.client.HttpClientSettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
/**
* The corrected form of the timeouts-and-interceptors snippet: HttpClientSettings replaces the
* ClientHttpRequestFactorySettings type the old article used (src/broken/OldTimeoutSettings.java
* shows the compiler error for that name).
*/
@Configuration(proxyBeanMethods = false)
public class RestClientConfig {
@Bean
RestClient apiClient(RestClient.Builder builder) {
HttpClientSettings settings = HttpClientSettings.defaults()
.withConnectTimeout(Duration.ofSeconds(2))
.withReadTimeout(Duration.ofSeconds(5)); // ALWAYS set timeouts
return builder
.requestFactory(ClientHttpRequestFactoryBuilder.detect().build(settings))
.requestInterceptor((request, body, execution) -> {
request.getHeaders().add("X-Request-Id", UUID.randomUUID().toString());
return execution.execute(request, body);
})
.build();
}
}
@@ -0,0 +1,12 @@
package com.ankurm.rtmigration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RtMigrationApplication {
public static void main(String[] args) {
SpringApplication.run(RtMigrationApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package com.ankurm.rtmigration;
/** The payload every client in this module sends and receives. */
public record Student(Integer id, String name) {
}
@@ -0,0 +1,32 @@
package com.ankurm.rtmigration;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.client.RestClient;
/**
* The "after": the same two operations on RestClient. The builder is injected so Boot's message
* converters, request factory, timeouts and observation settings apply; RestClient.create() would skip them.
*/
public class StudentClient {
private final RestClient restClient;
public StudentClient(RestClient.Builder builder, String base) {
this.restClient = builder.baseUrl(base).build();
}
public Student findById(int id) {
return this.restClient.get().uri("/students/{id}", id).retrieve().body(Student.class);
}
public List<Student> findAll(String token) {
return this.restClient.get()
.uri("/students")
.headers(h -> h.setBearerAuth(token))
.retrieve()
.body(new ParameterizedTypeReference<List<Student>>() {
});
}
}
@@ -0,0 +1,129 @@
package com.ankurm.rtmigration;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
/**
* A small real server for every client in this module to call. It is deliberately boring: the
* interesting part of each test is what the CLIENT does with these responses.
*/
@RestController
public class StudentController {
private final Map<Integer, Student> store = new ConcurrentHashMap<>();
private final AtomicInteger sequence = new AtomicInteger();
public StudentController() {
reset();
}
@PostMapping("/admin/reset")
void reset() {
this.store.clear();
this.sequence.set(2);
this.store.put(1, new Student(1, "Asha"));
this.store.put(2, new Student(2, "Ravi"));
}
@GetMapping("/students/{id}")
Student one(@PathVariable int id) {
Student s = this.store.get(id);
if (s == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No student " + id);
}
return s;
}
@GetMapping("/students")
List<Student> all() {
return this.store.values().stream().sorted((a, b) -> a.id() - b.id()).toList();
}
@PostMapping("/students")
ResponseEntity<Student> create(@RequestBody Student in) {
Student s = new Student(this.sequence.incrementAndGet(), in.name());
this.store.put(s.id(), s);
return ResponseEntity.created(URI.create("/students/" + s.id())).body(s);
}
@PutMapping("/students/{id}")
ResponseEntity<Void> replace(@PathVariable int id, @RequestBody Student in) {
this.store.put(id, new Student(id, in.name()));
return ResponseEntity.noContent().build();
}
@PatchMapping("/students/{id}")
Student patch(@PathVariable int id, @RequestBody Student in) {
Student s = new Student(id, in.name());
this.store.put(id, s);
return s;
}
@DeleteMapping("/students/{id}")
ResponseEntity<Void> delete(@PathVariable int id) {
this.store.remove(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/boom")
String boom() {
throw new IllegalStateException("kaboom");
}
@GetMapping("/empty")
ResponseEntity<Void> empty() {
return ResponseEntity.noContent().build();
}
/** What the server actually received: the headers a client library really put on the wire. */
@GetMapping("/whoami")
Map<String, String> whoami(HttpServletRequest request) {
Map<String, String> seen = new LinkedHashMap<>();
seen.put("user-agent", request.getHeader("user-agent"));
seen.put("authorization", request.getHeader("authorization"));
seen.put("x-request-id", request.getHeader("x-request-id"));
seen.put("accept", request.getHeader("accept"));
seen.put("protocol", request.getProtocol());
return seen;
}
/** Returns the raw query string and what Tomcat decoded from it. */
@GetMapping("/search")
Map<String, String> search(HttpServletRequest request, @RequestParam("q") String q) {
Map<String, String> seen = new LinkedHashMap<>();
seen.put("rawQuery", request.getQueryString());
seen.put("q", q);
return seen;
}
@GetMapping("/slow")
String slow(@RequestParam long ms) throws InterruptedException {
Thread.sleep(ms);
return "done after " + ms + " ms";
}
@GetMapping("/text")
String text() {
return "plain text body";
}
}
@@ -0,0 +1,47 @@
package com.ankurm.rtmigration.recipe;
import java.util.List;
import com.ankurm.rtmigration.Student;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
/**
* Not part of the build. The INPUT for scripts/openrewrite.sh: a typical RestTemplate client.
* The recipe's output replaces src/test/.../recipe/RemoteClient.java.
*/
public class RemoteClient {
private final RestTemplate restTemplate = new RestTemplate();
private final String base;
public RemoteClient(String base) {
this.base = base;
}
public Student find(int id) {
return this.restTemplate.getForObject(this.base + "/students/{id}", Student.class, id);
}
public ResponseEntity<Student> create(Student s) {
return this.restTemplate.postForEntity(this.base + "/students", s, Student.class);
}
public void remove(int id) {
this.restTemplate.delete(this.base + "/students/{id}", id);
}
public List<Student> all(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
return this.restTemplate.exchange(this.base + "/students", HttpMethod.GET, new HttpEntity<>(headers),
new ParameterizedTypeReference<List<Student>>() {
}).getBody();
}
}
@@ -0,0 +1,94 @@
package com.ankurm.rtmigration;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
/**
* RestClient.create(restTemplate): the supported way to migrate one call site at a time while
* the RestTemplate bean is still around. What the bridge carries over, and the one thing it does not.
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class BridgeTest {
@LocalServerPort
int port;
@Test
@SuppressWarnings("unchecked")
void whatTheBridgeCopies() {
Transcript t = new Transcript("05-bridge-what-is-copied");
String base = "http://localhost:" + this.port;
RestTemplate rt = new RestTemplate(new JdkClientHttpRequestFactory());
rt.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("X-Request-Id", "abc-123");
return execution.execute(request, body);
});
rt.setErrorHandler(new ErrorHandlingTest.NotFoundTranslatingHandler());
RestClient bridged = RestClient.create(rt);
RestClient fresh = RestClient.create();
Map<String, String> viaTemplate = rt.getForObject(base + "/whoami", Map.class);
Map<String, String> viaBridge = bridged.get().uri(base + "/whoami").retrieve().body(Map.class);
Map<String, String> viaFresh = fresh.get().uri(base + "/whoami").retrieve().body(Map.class);
t.line("GET /whoami, what the server received");
t.line(" RestTemplate(JdkClientHttpRequestFactory + interceptor): x-request-id=" + viaTemplate.get("x-request-id") + " user-agent=" + viaTemplate.get("user-agent"));
t.line(" RestClient.create(thatTemplate) : x-request-id=" + viaBridge.get("x-request-id") + " user-agent=" + viaBridge.get("user-agent"));
t.line(" RestClient.create() (no bridge) : x-request-id=" + viaFresh.get("x-request-id") + " user-agent=" + viaFresh.get("user-agent"));
assertThat(viaBridge.get("x-request-id")).isEqualTo("abc-123");
assertThat(viaBridge.get("user-agent")).isEqualTo(viaTemplate.get("user-agent"));
assertThat(viaFresh.get("x-request-id")).isNull();
Throwable b = catchThrowable(() -> bridged.get().uri(base + "/students/99").retrieve().body(Student.class));
t.line("GET /students/99 through the bridge, template had a custom ResponseErrorHandler -> " + b.getClass().getSimpleName());
assertThat(b).isInstanceOf(ErrorHandlingTest.StudentNotFoundException.class);
t.write();
}
@Test
@SuppressWarnings("unchecked")
void theBridgeDoesNotCarryUriEncodingOver() {
Transcript t = new Transcript("06-bridge-uri-encoding");
String base = "http://localhost:" + this.port;
RestTemplate rt = new RestTemplate();
EncodingMode legacyMode = ((DefaultUriBuilderFactory) rt.getUriTemplateHandler()).getEncodingMode();
t.line("RestTemplate default URI encoding mode : " + legacyMode);
t.line("RestClient default URI encoding mode : " + EncodingMode.TEMPLATE_AND_VALUES + " (DefaultUriBuilderFactory default)");
assertThat(legacyMode).isEqualTo(EncodingMode.URI_COMPONENT);
assertThat(new DefaultUriBuilderFactory().getEncodingMode()).isEqualTo(EncodingMode.TEMPLATE_AND_VALUES);
String q = "C++";
Map<String, String> a = rt.getForObject(base + "/search?q={q}", Map.class, q);
Map<String, String> b = RestClient.create(rt).get().uri(base + "/search?q={q}", q).retrieve().body(Map.class);
Map<String, String> c = RestClient.create().get().uri(base + "/search?q={q}", q).retrieve().body(Map.class);
DefaultUriBuilderFactory legacy = new DefaultUriBuilderFactory();
legacy.setEncodingMode(EncodingMode.URI_COMPONENT);
Map<String, String> d = RestClient.builder(rt).uriBuilderFactory(legacy).build()
.get().uri(base + "/search?q={q}", q).retrieve().body(Map.class);
t.line("");
t.line("variable q = \"C++\", template \"/search?q={q}\"");
t.line(" new RestTemplate() wire: " + a.get("rawQuery") + " server decoded q = \"" + a.get("q") + "\"");
t.line(" RestClient.create(restTemplate) wire: " + b.get("rawQuery") + " server decoded q = \"" + b.get("q") + "\"");
t.line(" RestClient.create() wire: " + c.get("rawQuery") + " server decoded q = \"" + c.get("q") + "\"");
t.line(" builder(rt).uriBuilderFactory(URI_COMPONENT) wire: " + d.get("rawQuery") + " server decoded q = \"" + d.get("q") + "\"");
assertThat(a.get("q")).isEqualTo("C ");
assertThat(b.get("q")).isEqualTo("C++");
assertThat(c.get("q")).isEqualTo("C++");
assertThat(d.get("q")).isEqualTo("C ");
t.write();
}
}
@@ -0,0 +1,36 @@
package com.ankurm.rtmigration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/** Which HTTP client beans spring-boot-starter-restclient registers on Boot 4.2.0. */
@SuppressWarnings("removal")
@SpringBootTest
class BuilderBeansTest {
@Autowired
ApplicationContext context;
@Test
void beansOnTheClasspath() {
Transcript t = new Transcript("12-auto-configured-beans");
t.line("RestClient.Builder beans : " + this.context.getBeanNamesForType(RestClient.Builder.class).length);
t.line("RestTemplateBuilder beans: " + this.context.getBeanNamesForType(RestTemplateBuilder.class).length);
t.line("RestTemplate beans : " + this.context.getBeanNamesForType(RestTemplate.class).length + " (Boot never registers a RestTemplate itself)");
RestClient.Builder one = this.context.getBean(RestClient.Builder.class);
RestClient.Builder two = this.context.getBean(RestClient.Builder.class);
t.line("two getBean(RestClient.Builder) calls return the same instance: " + (one == two) + " (prototype scope: configure your copy freely)");
assertThat(this.context.getBeanNamesForType(RestClient.Builder.class)).hasSize(1);
assertThat(this.context.getBeanNamesForType(RestTemplateBuilder.class)).hasSize(1);
assertThat(this.context.getBeanNamesForType(RestTemplate.class)).isEmpty();
assertThat(one).isNotSameAs(two);
t.write();
}
}
@@ -0,0 +1,33 @@
package com.ankurm.rtmigration;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.web.client.RestClient;
import static org.assertj.core.api.Assertions.assertThat;
/** The RestClientConfig bean: the interceptor's header reaches the server and the call works. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ConfiguredClientTest {
@LocalServerPort
int port;
@Autowired
RestClient apiClient;
@Test
@SuppressWarnings("unchecked")
void interceptorHeaderReachesTheServer() {
Transcript t = new Transcript("22-configured-client");
Map<String, String> seen = this.apiClient.get().uri("http://localhost:" + this.port + "/whoami").retrieve().body(Map.class);
String id = seen.get("x-request-id");
t.line("RestClientConfig.apiClient GET /whoami -> server saw x-request-id: <" + (id != null && id.length() == 36 ? "36-character UUID" : id) + ">");
assertThat(id).hasSize(36);
t.write();
}
}
@@ -0,0 +1,167 @@
package com.ankurm.rtmigration;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URI;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* What each client throws for a 404, a 500 and a refused connection, and how a custom
* ResponseErrorHandler moves to defaultStatusHandler / onStatus.
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ErrorHandlingTest {
@LocalServerPort
int port;
static class StudentNotFoundException extends RuntimeException {
StudentNotFoundException(String message) {
super(message);
}
}
/** The kind of handler a RestTemplate codebase centralises its error handling in. */
static class NotFoundTranslatingHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
if (response.getStatusCode().value() == 404) {
throw new StudentNotFoundException("no such resource: " + url.getPath());
}
super.handleError(url, method, response);
}
}
@Test
void defaultsAreTheSameExceptionTypes() {
Transcript t = new Transcript("02-error-defaults");
String base = "http://localhost:" + this.port;
RestTemplate rt = new RestTemplate();
RestClient rc = RestClient.create();
Throwable a = catchThrowable(() -> rt.getForObject(base + "/students/99", Student.class));
Throwable b = catchThrowable(() -> rc.get().uri(base + "/students/99").retrieve().body(Student.class));
describe(t, "GET /students/99 (404)", a, b);
assertThat(a).isInstanceOf(HttpClientErrorException.NotFound.class);
assertThat(b).isInstanceOf(HttpClientErrorException.NotFound.class);
assertThat(mask(((RestClientResponseException) a).getResponseBodyAsString()))
.isEqualTo(mask(((RestClientResponseException) b).getResponseBodyAsString()));
Throwable c = catchThrowable(() -> rt.getForObject(base + "/boom", String.class));
Throwable d = catchThrowable(() -> rc.get().uri(base + "/boom").retrieve().body(String.class));
describe(t, "GET /boom (500)", c, d);
assertThat(c).isInstanceOf(HttpServerErrorException.InternalServerError.class);
assertThat(d).isInstanceOf(HttpServerErrorException.InternalServerError.class);
int dead = freePort();
Throwable e = catchThrowable(() -> rt.getForObject("http://localhost:" + dead + "/x", String.class));
Throwable f = catchThrowable(() -> rc.get().uri("http://localhost:" + dead + "/x").retrieve().body(String.class));
t.line("connection refused (nothing listening)");
t.line(" RestTemplate : " + e.getClass().getName() + " <- cause " + e.getCause().getClass().getName());
t.line(" RestClient : " + f.getClass().getName() + " <- cause " + f.getCause().getClass().getName());
assertThat(e).isInstanceOf(ResourceAccessException.class);
assertThat(f).isInstanceOf(ResourceAccessException.class);
assertThat(e.getCause().getClass()).isEqualTo(f.getCause().getClass());
String x = rt.getForObject(base + "/empty", String.class);
String y = rc.get().uri(base + "/empty").retrieve().body(String.class);
t.line("204 No Content body: RestTemplate.getForObject -> " + x + ", RestClient.body(String.class) -> " + y);
assertThat(x).isNull();
assertThat(y).isNull();
t.write();
}
@Test
void customHandlerMovesToDefaultStatusHandler() {
Transcript t = new Transcript("03-error-handler-migration");
String base = "http://localhost:" + this.port;
RestTemplate rt = new RestTemplate();
rt.setErrorHandler(new NotFoundTranslatingHandler());
// Option 1: reuse the very same handler object on the builder
RestClient reuse = RestClient.builder().defaultStatusHandler(new NotFoundTranslatingHandler()).build();
// Option 2: express it as a predicate + lambda
RestClient lambda = RestClient.builder()
.defaultStatusHandler(code -> code.value() == 404, (req, res) -> {
throw new StudentNotFoundException("no such resource: " + req.getURI().getPath());
})
.build();
// Option 3: per call
RestClient plain = RestClient.create();
Throwable a = catchThrowable(() -> rt.getForObject(base + "/students/99", Student.class));
Throwable b = catchThrowable(() -> reuse.get().uri(base + "/students/99").retrieve().body(Student.class));
Throwable c = catchThrowable(() -> lambda.get().uri(base + "/students/99").retrieve().body(Student.class));
Throwable d = catchThrowable(() -> plain.get().uri(base + "/students/99").retrieve()
.onStatus(code -> code.value() == 404, (req, res) -> {
throw new StudentNotFoundException("no such resource: " + req.getURI().getPath());
})
.body(Student.class));
t.line("GET /students/99 with a custom 404 translation");
t.line(" RestTemplate.setErrorHandler(handler) -> " + a.getClass().getSimpleName() + ": " + a.getMessage());
t.line(" builder.defaultStatusHandler(<same handler>) -> " + b.getClass().getSimpleName() + ": " + b.getMessage());
t.line(" builder.defaultStatusHandler(predicate, lambda) -> " + c.getClass().getSimpleName() + ": " + c.getMessage());
t.line(" retrieve().onStatus(predicate, lambda) per call -> " + d.getClass().getSimpleName() + ": " + d.getMessage());
assertThat(List.of(a, b, c, d)).allSatisfy(x -> assertThat(x).isInstanceOf(StudentNotFoundException.class));
// statuses the custom handler does not claim still get the framework default
Throwable e = catchThrowable(() -> rt.getForObject(base + "/boom", String.class));
Throwable f = catchThrowable(() -> reuse.get().uri(base + "/boom").retrieve().body(String.class));
Throwable g = catchThrowable(() -> lambda.get().uri(base + "/boom").retrieve().body(String.class));
t.line("GET /boom (500), not claimed by the custom handler");
t.line(" RestTemplate -> " + e.getClass().getName());
t.line(" defaultStatusHandler(<handler>) -> " + f.getClass().getName());
t.line(" defaultStatusHandler(pred, lambda)-> " + g.getClass().getName());
assertThat(e).isInstanceOf(HttpServerErrorException.class);
assertThat(f).isInstanceOf(HttpServerErrorException.class);
assertThat(g).isInstanceOf(HttpServerErrorException.class);
t.write();
}
private static void describe(Transcript t, String title, Throwable a, Throwable b) {
t.line(title);
t.line(" RestTemplate : " + a.getClass().getName());
t.line(" RestClient : " + b.getClass().getName());
t.line(" RestTemplate message : " + mask(a.getMessage()));
t.line(" RestClient message : " + mask(b.getMessage()));
t.line(" same message: " + mask(a.getMessage()).equals(mask(b.getMessage())));
}
/** The server stamps each error body with the time; hide it so the two bodies can be compared and committed. */
private static String mask(String s) {
return s.replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"<time>\"").replaceAll("localhost:\\d+", "localhost:<port>");
}
private static Throwable catchThrowable(Runnable r) {
return org.assertj.core.api.Assertions.catchThrowable(r::run);
}
private static int freePort() {
try (ServerSocket s = new ServerSocket(0)) {
return s.getLocalPort();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
@@ -0,0 +1,71 @@
package com.ankurm.rtmigration;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
/**
* The rename that compiles and silently changes behaviour: restTemplate.exchange(...) becomes
* restClient...exchange(...) instead of retrieve().
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ExchangeTrapTest {
@LocalServerPort
int port;
@Test
void exchangeDoesNotApplyTheDefaultStatusHandlers() {
Transcript t = new Transcript("04-exchange-trap");
String base = "http://localhost:" + this.port;
RestTemplate rt = new RestTemplate();
RestClient rc = RestClient.create();
// RestTemplate.exchange on a 404 throws
Throwable a = catchThrowable(() -> rt.exchange(base + "/students/99", HttpMethod.GET, null, Student.class));
t.line("RestTemplate.exchange(GET /students/99) -> throws " + a.getClass().getSimpleName());
assertThat(a).isInstanceOf(HttpClientErrorException.NotFound.class);
// retrieve() on a 404 throws
Throwable b = catchThrowable(() -> rc.get().uri(base + "/students/99").retrieve().body(Student.class));
t.line("RestClient.get()...retrieve().body(...) -> throws " + b.getClass().getSimpleName());
assertThat(b).isInstanceOf(HttpClientErrorException.NotFound.class);
// the mechanical rename: exchange(...) with a body-reading lambda does NOT throw
Student[] got = new Student[1];
Throwable c = catchThrowable(() -> got[0] = rc.get().uri(base + "/students/99")
.exchange((req, res) -> res.bodyTo(Student.class)));
t.line("RestClient.get()...exchange((req, res) -> res.bodyTo(Student.class))");
t.line(" -> throws: " + (c == null ? "nothing" : c.getClass().getSimpleName()) + "; returned " + got[0]);
assertThat(c).isNull();
assertThat(got[0]).isEqualTo(new Student(null, null));
// 500 the same way
String[] seen = new String[1];
rc.get().uri(base + "/boom").exchange((req, res) -> {
seen[0] = res.getStatusCode() + " " + res.bodyTo(String.class).replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"<time>\"");
return null;
});
t.line("RestClient.get()...exchange(...) on GET /boom -> no exception; handler saw " + seen[0]);
assertThat(seen[0]).startsWith("500 INTERNAL_SERVER_ERROR");
// the fix when raw access is genuinely needed: check the status yourself
Throwable d = catchThrowable(() -> rc.get().uri(base + "/students/99").exchange((req, res) -> {
if (res.getStatusCode().isError()) {
throw new IllegalStateException("HTTP " + res.getStatusCode().value() + " for " + req.getURI().getPath());
}
return res.bodyTo(Student.class);
}));
t.line("exchange(...) with an explicit isError() check -> " + d.getClass().getSimpleName() + ": " + d.getMessage());
assertThat(d).isInstanceOf(IllegalStateException.class);
t.write();
}
}
@@ -0,0 +1,71 @@
package com.ankurm.rtmigration;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* An interceptor that logs the response body consumes it. Same trap on both clients; the
* RestClient fix is one builder call, bufferContent(...).
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class InterceptorBufferingTest {
@LocalServerPort
int port;
private static ClientHttpRequestInterceptor bodyLogger(List<String> log) {
return (request, body, execution) -> {
ClientHttpResponse response = execution.execute(request, body);
log.add(new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8));
return response;
};
}
@Test
void loggingInterceptorEatsTheBody() {
Transcript t = new Transcript("08-interceptor-reads-body");
String url = "http://localhost:" + this.port + "/text";
List<String> log = new ArrayList<>();
RestTemplate plain = new RestTemplate();
plain.getInterceptors().add(bodyLogger(log));
RestTemplate buffered = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
buffered.getInterceptors().add(bodyLogger(log));
RestClient rcPlain = RestClient.builder().requestInterceptor(bodyLogger(log)).build();
RestClient rcBuffered = RestClient.builder().requestInterceptor(bodyLogger(log)).bufferContent((uri, method) -> true).build();
String r1 = plain.getForObject(url, String.class);
String r2 = buffered.getForObject(url, String.class);
String r3 = rcPlain.get().uri(url).retrieve().body(String.class);
String r4 = rcBuffered.get().uri(url).retrieve().body(String.class);
t.line("GET /text (server body: \"plain text body\"); the interceptor reads the body to log it");
t.line(" RestTemplate, default factory -> caller got " + show(r1));
t.line(" RestTemplate + BufferingClientHttpRequestFactory -> caller got " + show(r2));
t.line(" RestClient, interceptor only -> caller got " + show(r3));
t.line(" RestClient + bufferContent((uri, method) -> true) -> caller got " + show(r4));
t.line("interceptor logged: " + log);
assertThat(r2).isEqualTo("plain text body");
assertThat(r4).isEqualTo("plain text body");
assertThat(log).hasSize(4).containsOnly("plain text body");
t.write();
}
private static String show(String s) {
return s == null ? "null" : "\"" + s + "\"";
}
}
@@ -0,0 +1,164 @@
package com.ankurm.rtmigration;
import java.net.URI;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Every row of the method-mapping table in the article, executed: the RestTemplate call and its
* RestClient equivalent run against the same real server, and the results are compared.
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MethodMappingTest {
@LocalServerPort
int port;
String base;
final RestTemplate rt = new RestTemplate();
final RestClient rc = RestClient.create();
@BeforeEach
void reset() {
this.base = "http://localhost:" + this.port;
this.rc.post().uri(this.base + "/admin/reset").retrieve().toBodilessEntity();
}
@Test
void everyRowOfTheMappingTable() {
Transcript t = new Transcript("01-method-mapping");
t.line("server: StudentController on http://localhost:<random port>, seeded with 1=Asha, 2=Ravi");
t.line("");
// getForObject
Student a = this.rt.getForObject(this.base + "/students/{id}", Student.class, 1);
Student b = this.rc.get().uri(this.base + "/students/{id}", 1).retrieve().body(Student.class);
row(t, "getForObject(url, Student.class, 1)", "get().uri(url, 1).retrieve().body(Student.class)", a, b);
assertThat(a).isEqualTo(b).isEqualTo(new Student(1, "Asha"));
// getForEntity
ResponseEntity<Student> ea = this.rt.getForEntity(this.base + "/students/{id}", Student.class, 2);
ResponseEntity<Student> eb = this.rc.get().uri(this.base + "/students/{id}", 2).retrieve().toEntity(Student.class);
String sa = ea.getStatusCode() + " " + ea.getHeaders().getContentType() + " " + ea.getBody();
String sb = eb.getStatusCode() + " " + eb.getHeaders().getContentType() + " " + eb.getBody();
row(t, "getForEntity(url, Student.class, 2)", "get().uri(url, 2).retrieve().toEntity(Student.class)", sa, sb);
assertThat(sa).isEqualTo(sb);
// postForObject
this.reset();
Student pa = this.rt.postForObject(this.base + "/students", new Student(null, "Meera"), Student.class);
this.reset();
Student pb = this.rc.post().uri(this.base + "/students").body(new Student(null, "Meera")).retrieve().body(Student.class);
row(t, "postForObject(url, request, Student.class)", "post().uri(url).body(request).retrieve().body(Student.class)", pa, pb);
assertThat(pa).isEqualTo(pb).isEqualTo(new Student(3, "Meera"));
// postForEntity
this.reset();
ResponseEntity<Student> xa = this.rt.postForEntity(this.base + "/students", new Student(null, "Kabir"), Student.class);
this.reset();
ResponseEntity<Student> xb = this.rc.post().uri(this.base + "/students").body(new Student(null, "Kabir")).retrieve().toEntity(Student.class);
String xsa = xa.getStatusCode() + " " + xa.getHeaders().getLocation() + " " + xa.getBody();
String xsb = xb.getStatusCode() + " " + xb.getHeaders().getLocation() + " " + xb.getBody();
row(t, "postForEntity(url, request, Student.class)", "post().uri(url).body(request).retrieve().toEntity(Student.class)", xsa, xsb);
assertThat(xsa).isEqualTo(xsb);
// postForLocation
this.reset();
URI la = this.rt.postForLocation(this.base + "/students", new Student(null, "Zoya"));
this.reset();
URI lb = this.rc.post().uri(this.base + "/students").body(new Student(null, "Zoya")).retrieve().toBodilessEntity().getHeaders().getLocation();
row(t, "postForLocation(url, request)", "post().uri(url).body(request).retrieve().toBodilessEntity().getHeaders().getLocation()", la, lb);
assertThat(la).isEqualTo(lb);
// put
this.reset();
this.rt.put(this.base + "/students/{id}", new Student(null, "Asha K"), 1);
String afterRt = this.rt.getForObject(this.base + "/students/1", Student.class).name();
this.reset();
ResponseEntity<Void> put = this.rc.put().uri(this.base + "/students/{id}", 1).body(new Student(null, "Asha K")).retrieve().toBodilessEntity();
String afterRc = this.rc.get().uri(this.base + "/students/1").retrieve().body(Student.class).name();
row(t, "put(url, request, 1)", "put().uri(url, 1).body(request).retrieve().toBodilessEntity()", afterRt, afterRc + " (status " + put.getStatusCode() + ")");
assertThat(afterRt).isEqualTo(afterRc).isEqualTo("Asha K");
// delete
this.reset();
this.rt.delete(this.base + "/students/{id}", 1);
int goneRt = status(this.base + "/students/1");
this.reset();
ResponseEntity<Void> del = this.rc.delete().uri(this.base + "/students/{id}", 1).retrieve().toBodilessEntity();
int goneRc = status(this.base + "/students/1");
row(t, "delete(url, 1)", "delete().uri(url, 1).retrieve().toBodilessEntity()", "then GET -> " + goneRt, "then GET -> " + goneRc + " (delete status " + del.getStatusCode() + ")");
assertThat(goneRt).isEqualTo(404).isEqualTo(goneRc);
// headForHeaders / optionsForAllow
this.reset();
HttpHeaders ha = this.rt.headForHeaders(this.base + "/students/{id}", 1);
HttpHeaders hb = this.rc.head().uri(this.base + "/students/{id}", 1).retrieve().toBodilessEntity().getHeaders();
row(t, "headForHeaders(url, 1) content-type", "head().uri(url, 1).retrieve().toBodilessEntity().getHeaders()", ha.getContentType(), hb.getContentType());
assertThat(ha.getContentType()).isEqualTo(hb.getContentType());
Set<HttpMethod> oa = this.rt.optionsForAllow(this.base + "/students");
Set<HttpMethod> ob = this.rc.options().uri(this.base + "/students").retrieve().toBodilessEntity().getHeaders().getAllow();
row(t, "optionsForAllow(url)", "options().uri(url).retrieve().toBodilessEntity().getHeaders().getAllow()", Set.copyOf(oa).stream().sorted().toList(), Set.copyOf(ob).stream().sorted().toList());
assertThat(oa).containsExactlyInAnyOrderElementsOf(ob);
// exchange with headers + ParameterizedTypeReference
HttpHeaders h = new HttpHeaders();
h.setBearerAuth("tok-123");
List<Student> la1 = this.rt.exchange(this.base + "/students", HttpMethod.GET, new HttpEntity<>(h),
new ParameterizedTypeReference<List<Student>>() {
}).getBody();
List<Student> lb1 = this.rc.get().uri(this.base + "/students").headers(x -> x.setBearerAuth("tok-123")).retrieve()
.body(new ParameterizedTypeReference<List<Student>>() {
});
row(t, "exchange(url, GET, new HttpEntity<>(headers), new ParameterizedTypeReference<List<Student>>() {})",
"get().uri(url).headers(h -> ...).retrieve().body(new ParameterizedTypeReference<List<Student>>() {})", la1, lb1);
assertThat(la1).isEqualTo(lb1).hasSize(2);
// the bearer token really reached the server
String seenRt = this.rt.exchange(this.base + "/whoami", HttpMethod.GET, new HttpEntity<>(h), String.class).getBody();
String seenRc = this.rc.get().uri(this.base + "/whoami").headers(x -> x.setBearerAuth("tok-123")).retrieve().body(String.class);
assertThat(seenRt).contains("\"authorization\":\"Bearer tok-123\"");
assertThat(seenRc).contains("\"authorization\":\"Bearer tok-123\"");
t.line("");
t.line("server saw Authorization on both: Bearer tok-123");
// the two client classes of the article, side by side
LegacyStudentClient legacy = new LegacyStudentClient(new RestTemplate(), this.base);
StudentClient modern = new StudentClient(RestClient.builder(), this.base);
assertThat(legacy.findById(1)).isEqualTo(modern.findById(1));
assertThat(legacy.findAll("tok")).isEqualTo(modern.findAll("tok"));
t.line("LegacyStudentClient.findById(1) == StudentClient.findById(1): true");
t.line("LegacyStudentClient.findAll(token) == StudentClient.findAll(token): true");
t.write();
}
private int status(String url) {
return this.rc.get().uri(url).exchange((req, res) -> res.getStatusCode().value());
}
private static void row(Transcript t, String old, String neu, Object a, Object b) {
t.line("RestTemplate " + old);
t.line(" -> " + a);
t.line("RestClient " + neu);
t.line(" -> " + b + " same result: " + a.toString().equals(b.toString().replaceAll(" \\(.*\\)$", "")) );
t.line("");
}
}
@@ -0,0 +1,44 @@
package com.ankurm.rtmigration;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
/**
* Unit tests that mock the HTTP layer: MockRestServiceServer binds to a RestClient.Builder the
* same way it binds to a RestTemplate, so those tests port without changing the expectations.
*/
@SuppressWarnings("removal")
class MockServerTest {
@Test
void bindToTemplateAndBindToBuilder() {
Transcript t = new Transcript("11-mock-server");
RestTemplate rt = new RestTemplate();
MockRestServiceServer s1 = MockRestServiceServer.bindTo(rt).build();
s1.expect(requestTo("http://api.test/students/1")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("{\"id\":1,\"name\":\"Asha\"}", MediaType.APPLICATION_JSON));
Student a = rt.getForObject("http://api.test/students/1", Student.class);
s1.verify();
t.line("MockRestServiceServer.bindTo(restTemplate) -> " + a);
RestClient.Builder builder = RestClient.builder();
MockRestServiceServer s2 = MockRestServiceServer.bindTo(builder).build();
s2.expect(requestTo("http://api.test/students/1")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("{\"id\":1,\"name\":\"Asha\"}", MediaType.APPLICATION_JSON));
Student b = new StudentClient(builder, "http://api.test").findById(1);
s2.verify();
t.line("MockRestServiceServer.bindTo(restClientBuilder) -> " + b);
assertThat(a).isEqualTo(b);
t.write();
}
}
@@ -0,0 +1,53 @@
package com.ankurm.rtmigration;
import java.util.function.Supplier;
import com.ankurm.rtmigration.recipe.RemoteClient;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Runs the class OpenRewrite generated (src/test/.../recipe/RemoteClient.java, produced by
* scripts/openrewrite.sh from src/recipe/before/RemoteClient.java) against the real server.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RecipeOutputTest {
@LocalServerPort
int port;
@Test
void generatedClientAgainstTheRealServer() {
Transcript t = new Transcript("21-openrewrite-generated-client-run");
RemoteClient client = new RemoteClient("http://localhost:" + this.port);
String find = run(() -> client.find(1).toString());
t.line("find(1) -> " + find);
assertThat(find).isEqualTo("Student[id=1, name=Asha]");
String create = run(() -> client.create(new Student(null, "Meera")).getStatusCode().toString());
t.line("create(Meera) -> " + create);
String remove = run(() -> {
client.remove(1);
return "ok";
});
t.line("remove(1) -> " + remove);
String all = run(() -> client.all("tok").toString());
t.line("all(\"tok\") -> " + all.replaceAll("localhost:\\d+", "localhost:<port>"));
t.write();
}
private static String run(Supplier<String> call) {
try {
return call.get();
}
catch (RuntimeException ex) {
return "THROWS " + ex.getClass().getName() + ": " + ex.getMessage();
}
}
}
@@ -0,0 +1,75 @@
package com.ankurm.rtmigration;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
/**
* "Same blocking model" does not mean "same HTTP stack": the default request factory is
* different, which the server can see in the User-Agent header and in what PATCH does.
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class RequestFactoryTest {
@LocalServerPort
int port;
@Autowired
RestClient.Builder bootBuilder;
@Autowired
RestTemplateBuilder bootTemplateBuilder;
@Test
@SuppressWarnings("unchecked")
void defaultStacksAndPatch() {
Transcript t = new Transcript("07-default-request-factories");
String base = "http://localhost:" + this.port;
RestTemplate plain = new RestTemplate();
RestClient created = RestClient.create();
RestClient viaBoot = this.bootBuilder.build();
RestTemplate viaBootTemplate = this.bootTemplateBuilder.build();
t.line("request factory class on RestTemplate: new RestTemplate() -> " + plain.getRequestFactory().getClass().getName());
t.line("request factory class on RestTemplate: RestTemplateBuilder.build() -> " + viaBootTemplate.getRequestFactory().getClass().getName());
t.line("");
t.line("User-Agent the server received (GET /whoami)");
String ua1 = ((Map<String, String>) plain.getForObject(base + "/whoami", Map.class)).get("user-agent");
String ua2 = ((Map<String, String>) created.get().uri(base + "/whoami").retrieve().body(Map.class)).get("user-agent");
String ua3 = ((Map<String, String>) viaBoot.get().uri(base + "/whoami").retrieve().body(Map.class)).get("user-agent");
String ua4 = ((Map<String, String>) viaBootTemplate.getForObject(base + "/whoami", Map.class)).get("user-agent");
t.line(" new RestTemplate() : " + ua1);
t.line(" RestClient.create() : " + ua2);
t.line(" injected RestClient.Builder (Boot) : " + ua3);
t.line(" RestTemplateBuilder.build() (Boot) : " + ua4);
assertThat(ua1).startsWith("Java/");
assertThat(ua2).startsWith("Java-http-client/");
assertThat(ua3).startsWith("Java-http-client/");
assertThat(ua4).isEqualTo(ua3);
t.line("");
t.line("PATCH /students/1");
Throwable a = catchThrowable(() -> plain.patchForObject(base + "/students/1", new Student(null, "Asha P"), Student.class));
t.line(" new RestTemplate().patchForObject(...) -> " + (a == null ? "ok" : a.getClass().getSimpleName() + ": " + a.getMessage().replaceAll("localhost:\\d+", "localhost:<port>")));
assertThat(a).isNotNull();
Student b = created.patch().uri(base + "/students/1").body(new Student(null, "Asha P")).retrieve().body(Student.class);
t.line(" RestClient.create().patch()...body(Student) -> " + b);
assertThat(b).isEqualTo(new Student(1, "Asha P"));
Student c = new RestTemplate(new JdkClientHttpRequestFactory()).patchForObject(base + "/students/1", new Student(null, "Asha Q"), Student.class);
t.line(" new RestTemplate(new JdkClientHttpRequestFactory()).patchForObject(...) -> " + c);
assertThat(c).isEqualTo(new Student(1, "Asha Q"));
t.write();
}
}
@@ -0,0 +1,69 @@
package com.ankurm.rtmigration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.resttestclient.TestRestTemplate;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.servlet.client.RestTestClient;
import static org.assertj.core.api.Assertions.assertThat;
/**
* TestRestTemplate (deprecated for removal since Boot 4.2.0, removal planned 4.4.0) next to
* RestTestClient (Spring Framework 7.0+), asserting the same things against the same server.
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestRestTemplate
@AutoConfigureRestTestClient
class TestClientMigrationTest {
@Autowired
TestRestTemplate testRestTemplate;
@Autowired
RestTestClient restTestClient;
@Test
void sameAssertionsBothWays() {
Transcript t = new Transcript("10-test-clients");
ResponseEntity<Student> a = this.testRestTemplate.getForEntity("/students/1", Student.class);
t.line("TestRestTemplate.getForEntity(\"/students/1\", Student.class) -> " + a.getStatusCode() + " " + a.getBody());
assertThat(a.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(a.getBody()).isEqualTo(new Student(1, "Asha"));
Student[] seen = new Student[1];
this.restTestClient.get().uri("/students/1").exchange().expectStatus().isOk()
.expectBody(Student.class).value(s -> seen[0] = s);
t.line("RestTestClient.get().uri(\"/students/1\").exchange().expectStatus().isOk().expectBody(Student.class) -> " + seen[0]);
assertThat(seen[0]).isEqualTo(new Student(1, "Asha"));
ResponseEntity<String> b = this.testRestTemplate.getForEntity("/students/99", String.class);
t.line("TestRestTemplate on a 404 does not throw: status " + b.getStatusCode());
assertThat(b.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
this.restTestClient.get().uri("/students/99").exchange().expectStatus().isNotFound();
t.line("RestTestClient on a 404 does not throw: expectStatus().isNotFound() passed");
ResponseEntity<Student> c = this.testRestTemplate.postForEntity("/students", new Student(null, "Meera"), Student.class);
t.line("TestRestTemplate.postForEntity(...) -> " + c.getStatusCode() + " Location " + c.getHeaders().getLocation().getPath());
this.restTestClient.post().uri("/students").body(new Student(null, "Kabir")).exchange()
.expectStatus().isCreated().expectHeader().exists("Location");
t.line("RestTestClient.post()...body(...).exchange().expectStatus().isCreated().expectHeader().exists(\"Location\") passed");
assertThat(c.getStatusCode()).isEqualTo(HttpStatus.CREATED);
ResponseEntity<String> d = this.testRestTemplate.withBasicAuth("user", "pw").getForEntity("/whoami", String.class);
assertThat(d.getBody()).contains("\"authorization\":\"Basic dXNlcjpwdw==\"");
t.line("TestRestTemplate.withBasicAuth(\"user\", \"pw\") -> server saw Authorization: Basic dXNlcjpwdw==");
String[] auth = new String[1];
this.restTestClient.mutate().defaultHeaders(h -> h.setBasicAuth("user", "pw")).build()
.get().uri("/whoami").exchange().expectBody(String.class).value(s -> auth[0] = s);
assertThat(auth[0]).contains("\"authorization\":\"Basic dXNlcjpwdw==\"");
t.line("RestTestClient.mutate().defaultHeaders(h -> h.setBasicAuth(\"user\", \"pw\")) -> server saw Authorization: Basic dXNlcjpwdw==");
t.write();
}
}
@@ -0,0 +1,89 @@
package com.ankurm.rtmigration;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.boot.http.client.HttpClientSettings;
import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
/**
* Timeouts: the Boot property that configures RestClient.Builder and RestTemplateBuilder alike,
* and the programmatic form that replaces ClientHttpRequestFactorySettings.
*/
@SuppressWarnings("removal")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "spring.http.clients.connect-timeout=300ms", "spring.http.clients.read-timeout=300ms" })
class TimeoutsTest {
@LocalServerPort
int port;
@Autowired
RestClient.Builder builder;
@Autowired
RestTemplateBuilder templateBuilder;
@Test
void propertiesAndProgrammaticSettings() {
Transcript t = new Transcript("09-timeouts");
String slow = "http://localhost:" + this.port + "/slow?ms=1500";
t.line("server: GET /slow?ms=1500 sleeps 1500 ms");
t.line("application.properties equivalent: spring.http.clients.connect-timeout=300ms, spring.http.clients.read-timeout=300ms");
t.line("");
long[] ms = new long[3];
Throwable a = timed(ms, 0, () -> this.builder.build().get().uri(slow).retrieve().body(String.class));
Throwable b = timed(ms, 1, () -> this.templateBuilder.build().getForObject(slow, String.class));
RestClient programmatic = RestClient.builder()
.requestFactory(ClientHttpRequestFactoryBuilder.detect()
.build(HttpClientSettings.defaults().withConnectTimeout(Duration.ofMillis(300)).withReadTimeout(Duration.ofMillis(300))))
.build();
Throwable c = timed(ms, 2, () -> programmatic.get().uri(slow).retrieve().body(String.class));
t.line("injected RestClient.Builder (Boot properties) -> " + describe(a) + ", gave up after " + bucket(ms[0]));
t.line("RestTemplateBuilder.build() (same Boot properties) -> " + describe(b) + ", gave up after " + bucket(ms[1]));
t.line("RestClient.builder().requestFactory(detect().build(HttpClientSettings.defaults().withReadTimeout(300ms))) -> " + describe(c) + ", gave up after " + bucket(ms[2]));
assertThat(a).isInstanceOf(ResourceAccessException.class);
assertThat(b).isInstanceOf(ResourceAccessException.class);
assertThat(c).isInstanceOf(ResourceAccessException.class);
for (long v : ms) {
assertThat(v).isBetween(250L, 1200L);
}
// without any timeout the same call just waits
RestClient noTimeouts = RestClient.create();
long start = System.nanoTime();
String ok = noTimeouts.get().uri(slow).retrieve().body(String.class);
long took = (System.nanoTime() - start) / 1_000_000;
t.line("RestClient.create() (no timeouts configured) -> \"" + ok + "\", " + bucket(took));
assertThat(ok).isEqualTo("done after 1500 ms");
t.write();
}
private static Throwable timed(long[] ms, int i, Runnable call) {
long start = System.nanoTime();
Throwable t = catchThrowable(call::run);
ms[i] = (System.nanoTime() - start) / 1_000_000;
return t;
}
private static String describe(Throwable t) {
return t.getClass().getSimpleName() + " <- " + t.getCause().getClass().getName();
}
/** Timing is indicative, not a result: report it in coarse buckets so reruns diff cleanly. */
private static String bucket(long ms) {
return ms < 250 ? "<250 ms" : ms <= 1200 ? "roughly 300-1200 ms" : ">1200 ms";
}
}
@@ -0,0 +1,46 @@
package com.ankurm.rtmigration;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Collects lines and writes output/NN-name.txt (output/NN-name-on-4.1.3.txt on the 4.1
* baseline). The test asserts the same values it writes, so every figure in the article is an
* assertion that fails the build when it stops being true.
*/
final class Transcript {
static final String LABEL = System.getProperty("boot.label", "4.2.0");
static boolean is42() {
return LABEL.startsWith("4.2");
}
private final List<String> lines = new ArrayList<>();
private final Path file;
Transcript(String name) {
String suffix = is42() ? "" : "-on-" + LABEL;
this.file = Path.of("output", name + suffix + ".txt");
line("# " + name + " (Spring Boot " + LABEL + ", JDK " + Runtime.version().feature() + ")");
}
Transcript line(String s) {
this.lines.add(s);
return this;
}
void write() {
try {
Files.createDirectories(this.file.getParent());
Files.write(this.file, this.lines);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
@@ -0,0 +1,46 @@
package com.ankurm.rtmigration.recipe;
import java.util.List;
import com.ankurm.rtmigration.Student;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClient;
/**
* Not part of the build. The INPUT for scripts/openrewrite.sh: a typical RestTemplate client.
* The recipe's output replaces src/test/.../recipe/RemoteClient.java.
*/
public class RemoteClient {
private final RestClient restTemplate = RestClient.create();
private final String base;
public RemoteClient(String base) {
this.base = base;
}
public Student find(int id) {
return this.restTemplate.get().uri(this.base + "/students/{id}", id).retrieve().body(Student.class);
}
public ResponseEntity<Student> create(Student s) {
return this.restTemplate.post().uri(this.base + "/students").body(s).retrieve().toEntity(Student.class);
}
public void remove(int id) {
this.restTemplate.delete().uri(this.base + "/students/{id}", id).retrieve().toBodilessEntity();
}
public List<Student> all(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
return this.restTemplate.method(HttpMethod.GET).uri(this.base + "/students").headers(h -> h.addAll(new HttpEntity<>(headers).getHeaders())).body(new HttpEntity<>(headers).getBody()).retrieve().toEntity(new ParameterizedTypeReference<List<Student>>() {
}).getBody();
}
}