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
@@ -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();
}
}