diff --git a/README.md b/README.md index 7853a2e..ff47b2e 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ files. | 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 | | [`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 | diff --git a/resttemplate-to-restclient/README.md b/resttemplate-to-restclient/README.md new file mode 100644 index 0000000..7425b1a --- /dev/null +++ b/resttemplate-to-restclient/README.md @@ -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. diff --git a/resttemplate-to-restclient/output/01-method-mapping-on-4.1.3.txt b/resttemplate-to-restclient/output/01-method-mapping-on-4.1.3.txt new file mode 100644 index 0000000..95f5aaf --- /dev/null +++ b/resttemplate-to-restclient/output/01-method-mapping-on-4.1.3.txt @@ -0,0 +1,57 @@ +# 01-method-mapping (Spring Boot 4.1.3, JDK 25) +server: StudentController on http://localhost:, 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>() {}) + -> [Student[id=1, name=Asha], Student[id=2, name=Ravi]] +RestClient get().uri(url).headers(h -> ...).retrieve().body(new ParameterizedTypeReference>() {}) + -> [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 diff --git a/resttemplate-to-restclient/output/01-method-mapping.txt b/resttemplate-to-restclient/output/01-method-mapping.txt new file mode 100644 index 0000000..30af7bf --- /dev/null +++ b/resttemplate-to-restclient/output/01-method-mapping.txt @@ -0,0 +1,57 @@ +# 01-method-mapping (Spring Boot 4.2.0, JDK 25) +server: StudentController on http://localhost:, 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>() {}) + -> [Student[id=1, name=Asha], Student[id=2, name=Ravi]] +RestClient get().uri(url).headers(h -> ...).retrieve().body(new ParameterizedTypeReference>() {}) + -> [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 diff --git a/resttemplate-to-restclient/output/02-error-defaults-on-4.1.3.txt b/resttemplate-to-restclient/output/02-error-defaults-on-4.1.3.txt new file mode 100644 index 0000000..33b222b --- /dev/null +++ b/resttemplate-to-restclient/output/02-error-defaults-on-4.1.3.txt @@ -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:/students/99": "{"timestamp":"