From bcfa2e66763ab2ddbb6b37407e570d335a2f8129 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 16 May 2016 12:27:55 -0700 Subject: [PATCH] Make TestRestTemplate not extend RestTemplate Update TestRestTemplate so that it no longer directly extends RestTemplate. Prior to this commit it was possible that TestRestTemplate could interfere with user defined RestTemplate beans. TestRestTemplate offers the same methods as RestTemplate so should be a drop-in replacement. If access is needed to the actual underlying template the `getRestTemplate()` method should be used. Fixes gh-5915 --- ...igurationCustomFilterContextPathTests.java | 4 +- ...utoConfigurationCustomFilterPathTests.java | 4 +- ...rationCustomObjectMapperProviderTests.java | 4 +- ...gurationCustomServletContextPathTests.java | 4 +- ...toConfigurationCustomServletPathTests.java | 4 +- ...toConfigurationDefaultFilterPathTests.java | 4 +- ...oConfigurationDefaultServletPathTests.java | 4 +- ...onfigurationObjectMapperProviderTests.java | 4 +- ...figurationWithoutApplicationPathTests.java | 4 +- .../oauth2/OAuth2AutoConfigurationTests.java | 5 +- .../RemappedErrorViewIntegrationTests.java | 3 +- .../jersey/SampleJerseyApplicationTests.java | 3 +- .../ssl/SampleJettySslApplicationTests.java | 18 +- .../jetty/SampleJettyApplicationTests.java | 3 +- .../ssl/SampleJetty8SslApplicationTests.java | 18 +- .../jetty8/SampleJetty8ApplicationTests.java | 3 +- .../SampleJetty93ApplicationTests.java | 3 +- .../ssl/SampleTomcatSslApplicationTests.java | 18 +- .../tomcat/SampleTomcatApplicationTests.java | 3 +- .../SampleUndertowSslApplicationTests.java | 18 +- .../SampleUndertowApplicationTests.java | 3 +- .../boot/test/TestRestTemplate.java | 118 ++- .../SpringBootTestContextCustomizer.java | 3 +- .../test/web/client/TestRestTemplate.java | 848 +++++++++++++++++- .../web/client/TestRestTemplateTests.java | 68 +- 25 files changed, 1041 insertions(+), 130 deletions(-) diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java index 16a717662e..ac8f5bd1e7 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterContextPathTests.java @@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -60,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationCustomFilterContextPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java index 8d468c2a92..8f6d235838 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomFilterPathTests.java @@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationCustomFilterPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java index 5959918455..a5a21a740a 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomObjectMapperProviderTests.java @@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationCustomObjectMapperProviderTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java index 1edd097e8d..22fe14a257 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletContextPathTests.java @@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -60,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationCustomServletContextPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java index 4590cd463c..eecfe983b0 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationCustomServletPathTests.java @@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -60,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationCustomServletPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java index 34787ce8ed..7e869d7eb2 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultFilterPathTests.java @@ -37,13 +37,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -58,7 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationDefaultFilterPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java index 762c38665c..57169bddd3 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationDefaultServletPathTests.java @@ -37,13 +37,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationDefaultServletPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java index 078f8a2e43..9531a98976 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationObjectMapperProviderTests.java @@ -38,13 +38,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -59,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationObjectMapperProviderTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java index dbfae0dbcf..7f278fbb6b 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jersey/JerseyAutoConfigurationWithoutApplicationPathTests.java @@ -37,13 +37,13 @@ import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoCo import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -58,7 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class JerseyAutoConfigurationWithoutApplicationPathTests { @Autowired - private RestTemplate restTemplate; + private TestRestTemplate restTemplate; @Test public void contextLoads() { diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java index e7eb64d720..32a6807bef 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/OAuth2AutoConfigurationTests.java @@ -94,7 +94,6 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -327,7 +326,7 @@ public class OAuth2AutoConfigurationTests { private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { String baseUrl = "http://localhost:" + this.context.getEmbeddedServletContainer().getPort(); - RestTemplate rest = new TestRestTemplate(); + TestRestTemplate rest = new TestRestTemplate(); // First, verify the web endpoint can't be reached assertEndpointUnauthorized(baseUrl, rest); // Since we can't reach it, need to collect an authorization token @@ -371,7 +370,7 @@ public class OAuth2AutoConfigurationTests { return body; } - private void assertEndpointUnauthorized(String baseUrl, RestTemplate rest) { + private void assertEndpointUnauthorized(String baseUrl, TestRestTemplate rest) { URI uri = URI.create(baseUrl + "/secured"); ResponseEntity entity = rest .exchange(new RequestEntity(HttpMethod.GET, uri), String.class); diff --git a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java index e206aa4eb9..af60515178 100644 --- a/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java +++ b/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/RemappedErrorViewIntegrationTests.java @@ -34,7 +34,6 @@ import org.springframework.stereotype.Controller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -51,7 +50,7 @@ public class RemappedErrorViewIntegrationTests { @LocalServerPort private int port; - private RestTemplate template = new TestRestTemplate(); + private TestRestTemplate template = new TestRestTemplate(); @Test public void directAccessToErrorPage() throws Exception { diff --git a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java index d12d8a2090..56231576e9 100644 --- a/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jersey/src/test/java/sample/jersey/SampleJerseyApplicationTests.java @@ -26,7 +26,6 @@ import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -37,7 +36,7 @@ public class SampleJerseyApplicationTests { @LocalServerPort private int port; - private RestTemplate restTemplate = new TestRestTemplate(); + private TestRestTemplate restTemplate = new TestRestTemplate(); @Test public void contextLoads() { diff --git a/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java index 6b3534e149..ce9dc3a03c 100644 --- a/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty-ssl/src/test/java/sample/jetty/ssl/SampleJettySslApplicationTests.java @@ -16,11 +16,6 @@ package sample.jetty.ssl; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; @@ -51,16 +46,7 @@ public class SampleJettySslApplicationTests { @Test public void testHome() throws Exception { - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) - .setHttpClient(httpClient); + TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL); ResponseEntity entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); diff --git a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java index 27de27b131..997cb5b60b 100644 --- a/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty/src/test/java/sample/jetty/SampleJettyApplicationTests.java @@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StreamUtils; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -67,7 +66,7 @@ public class SampleJettyApplicationTests { requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity requestEntity = new HttpEntity(requestHeaders); - RestTemplate restTemplate = new TestRestTemplate(); + TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, diff --git a/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java index 1a5b6ed4d4..59d9e457f3 100644 --- a/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty8-ssl/src/test/java/sample/jetty8/ssl/SampleJetty8SslApplicationTests.java @@ -16,11 +16,6 @@ package sample.jetty8.ssl; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; @@ -51,16 +46,7 @@ public class SampleJetty8SslApplicationTests { @Test public void testHome() throws Exception { - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) - .setHttpClient(httpClient); + TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL); ResponseEntity entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); diff --git a/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java index bcb9ea2374..00fa720f4c 100644 --- a/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty8/src/test/java/sample/jetty8/SampleJetty8ApplicationTests.java @@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StreamUtils; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -66,7 +65,7 @@ public class SampleJetty8ApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity requestEntity = new HttpEntity(requestHeaders); - RestTemplate restTemplate = new TestRestTemplate(); + TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); diff --git a/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java b/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java index a8a09783c3..4ca1267a1c 100644 --- a/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-jetty93/src/test/java/sample/jetty93/SampleJetty93ApplicationTests.java @@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StreamUtils; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -66,7 +65,7 @@ public class SampleJetty93ApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity requestEntity = new HttpEntity(requestHeaders); - RestTemplate restTemplate = new TestRestTemplate(); + TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); diff --git a/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/ssl/SampleTomcatSslApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/ssl/SampleTomcatSslApplicationTests.java index 4e1719af3f..f7b42c68a6 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/ssl/SampleTomcatSslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat-ssl/src/test/java/sample/tomcat/ssl/SampleTomcatSslApplicationTests.java @@ -16,11 +16,6 @@ package sample.tomcat.ssl; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; @@ -46,16 +41,7 @@ public class SampleTomcatSslApplicationTests { @Test public void testHome() throws Exception { - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) - .setHttpClient(httpClient); + TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL); ResponseEntity entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); diff --git a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java index 394c3c92e6..6a6f7db6c8 100644 --- a/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-tomcat/src/test/java/sample/tomcat/SampleTomcatApplicationTests.java @@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StreamUtils; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -66,7 +65,7 @@ public class SampleTomcatApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity requestEntity = new HttpEntity(requestHeaders); - RestTemplate restTemplate = new TestRestTemplate(); + TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); diff --git a/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java index 5cbe036093..4318421720 100644 --- a/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow-ssl/src/test/java/sample/undertow/ssl/SampleUndertowSslApplicationTests.java @@ -16,11 +16,6 @@ package sample.undertow.ssl; -import org.apache.http.client.HttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,9 +23,9 @@ import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; @@ -51,16 +46,7 @@ public class SampleUndertowSslApplicationTests { @Test public void testHome() throws Exception { - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( - new SSLContextBuilder() - .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) - .build(); - - TestRestTemplate testRestTemplate = new TestRestTemplate(); - ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()) - .setHttpClient(httpClient); + TestRestTemplate testRestTemplate = new TestRestTemplate(HttpClientOption.SSL); ResponseEntity entity = testRestTemplate .getForEntity("https://localhost:" + this.port, String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); diff --git a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java index 146d6ab96b..ba3f71bc40 100644 --- a/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-undertow/src/test/java/sample/undertow/SampleUndertowApplicationTests.java @@ -35,7 +35,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StreamUtils; -import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -68,7 +67,7 @@ public class SampleUndertowApplicationTests { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Accept-Encoding", "gzip"); HttpEntity requestEntity = new HttpEntity(requestHeaders); - RestTemplate restTemplate = new TestRestTemplate(); + TestRestTemplate restTemplate = new TestRestTemplate(); ResponseEntity entity = restTemplate.exchange( "http://localhost:" + this.port, HttpMethod.GET, requestEntity, byte[].class); diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/TestRestTemplate.java b/spring-boot-test/src/main/java/org/springframework/boot/test/TestRestTemplate.java index 97462e4480..9a734cf0df 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/TestRestTemplate.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/TestRestTemplate.java @@ -16,6 +16,31 @@ package org.springframework.boot.test; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.config.RequestConfig.Builder; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.protocol.HttpContext; + +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.http.client.InterceptingClientHttpRequestFactory; +import org.springframework.util.Base64Utils; +import org.springframework.util.ClassUtils; +import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; /** @@ -30,15 +55,16 @@ import org.springframework.web.client.RestTemplate; * {@link org.springframework.boot.test.web.client.TestRestTemplate} */ @Deprecated -public class TestRestTemplate - extends org.springframework.boot.test.web.client.TestRestTemplate { +public class TestRestTemplate extends RestTemplate { + + private static final Charset UTF_8 = Charset.forName("UTF-8"); /** * Create a new {@link TestRestTemplate} instance. * @param httpClientOptions client options to use if the Apache HTTP Client is used */ public TestRestTemplate(HttpClientOption... httpClientOptions) { - super(convertOptions(httpClientOptions)); + this(null, null, httpClientOptions); } /** @@ -49,18 +75,28 @@ public class TestRestTemplate */ public TestRestTemplate(String username, String password, HttpClientOption... httpClientOptions) { - super(username, password, convertOptions(httpClientOptions)); + if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) { + setRequestFactory( + new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); + } + addAuthentication(username, password); + setErrorHandler(new DefaultResponseErrorHandler() { + @Override + public void handleError(ClientHttpResponse response) throws IOException { + } + }); + } - private static org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption[] convertOptions( - HttpClientOption[] options) { - org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption[] result = new org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption[options.length]; - for (int i = 0; i < options.length; i++) { - HttpClientOption option = options[i]; - result[i] = org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption - .valueOf(option.name()); + private void addAuthentication(String username, String password) { + if (username == null) { + return; } - return result; + List interceptors = Collections + .singletonList( + new BasicAuthorizationInterceptor(username, password)); + setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(), + interceptors)); } /** @@ -80,4 +116,62 @@ public class TestRestTemplate } + private static class BasicAuthorizationInterceptor + implements ClientHttpRequestInterceptor { + + private final String username; + + private final String password; + + BasicAuthorizationInterceptor(String username, String password) { + this.username = username; + this.password = (password == null ? "" : password); + } + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, + ClientHttpRequestExecution execution) throws IOException { + String token = Base64Utils.encodeToString( + (this.username + ":" + this.password).getBytes(UTF_8)); + request.getHeaders().add("Authorization", "Basic " + token); + return execution.execute(request, body); + } + + } + + /** + * {@link HttpComponentsClientHttpRequestFactory} to apply customizations. + */ + protected static class CustomHttpComponentsClientHttpRequestFactory + extends HttpComponentsClientHttpRequestFactory { + + private final String cookieSpec; + + private final boolean enableRedirects; + + public CustomHttpComponentsClientHttpRequestFactory( + HttpClientOption[] httpClientOptions) { + Set options = new HashSet( + Arrays.asList(httpClientOptions)); + this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) + ? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES); + this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS); + } + + @Override + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + HttpClientContext context = HttpClientContext.create(); + context.setRequestConfig(getRequestConfig()); + return context; + } + + protected RequestConfig getRequestConfig() { + Builder builder = RequestConfig.custom().setCookieSpec(this.cookieSpec) + .setAuthenticationEnabled(false) + .setRedirectsEnabled(this.enableRedirects); + return builder.build(); + } + + } + } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java index d351a812b9..166e1d5b44 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootTestContextCustomizer.java @@ -23,7 +23,6 @@ import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextCustomizer; import org.springframework.test.context.MergedContextConfiguration; -import org.springframework.web.client.RestTemplate; /** * {@link ContextCustomizer} for {@link SpringBootTest}. @@ -39,7 +38,7 @@ class SpringBootTestContextCustomizer implements ContextCustomizer { SpringBootTest annotation = AnnotatedElementUtils.getMergedAnnotation( mergedContextConfiguration.getTestClass(), SpringBootTest.class); if (annotation.webEnvironment().isEmbedded()) { - RestTemplate restTemplate = TestRestTemplateFactory + Object restTemplate = TestRestTemplateFactory .createRestTemplate(context.getEnvironment()); context.getBeanFactory().registerSingleton("testRestTemplate", restTemplate); } diff --git a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java index e61b3c633a..91abccceab 100644 --- a/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java +++ b/spring-boot-test/src/main/java/org/springframework/boot/test/web/client/TestRestTemplate.java @@ -23,40 +23,63 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; +import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig.Builder; import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; +import org.apache.http.ssl.SSLContextBuilder; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.InterceptingClientHttpRequestFactory; +import org.springframework.util.Assert; import org.springframework.util.Base64Utils; import org.springframework.util.ClassUtils; import org.springframework.web.client.DefaultResponseErrorHandler; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.ResponseExtractor; +import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.DefaultUriTemplateHandler; +import org.springframework.web.util.UriTemplateHandler; /** - * Convenient subclass of {@link RestTemplate} that is suitable for integration tests. + * Convenient alternative of {@link RestTemplate} that is suitable for integration tests. * They are fault tolerant, and optionally can carry Basic authentication headers. If * Apache Http Client 4.3.2 or better is available (recommended) it will be used as the * client, and by default configured to ignore cookies and redirects. + *

+ * Note: To prevent injection problems this class internationally does not extend + * {@link RestTemplate}. If you need access to the underlying {@link RestTemplate} use + * {@link #getRestTemplate()}. * * @author Dave Syer * @author Phillip Webb * @since 1.4.0 */ -public class TestRestTemplate extends RestTemplate { +public class TestRestTemplate { private static final Charset UTF_8 = Charset.forName("UTF-8"); + private final RestTemplate restTemplate; + /** * Create a new {@link TestRestTemplate} instance. * @param httpClientOptions client options to use if the Apache HTTP Client is used @@ -73,28 +96,798 @@ public class TestRestTemplate extends RestTemplate { */ public TestRestTemplate(String username, String password, HttpClientOption... httpClientOptions) { + this.restTemplate = createRestTemplate(username, password, httpClientOptions); + } + + /** + * Factory method used to create the underlying {@link RestTemplate}. + * @param username the username to use (or {@code null}) + * @param password the password (or {@code null}) + * @param httpClientOptions client options to use if the Apache HTTP Client is used + * @return the delegate {@link RestTemplate} + */ + protected RestTemplate createRestTemplate(String username, String password, + HttpClientOption... httpClientOptions) { + RestTemplate restTemplate = new RestTemplate(); if (ClassUtils.isPresent("org.apache.http.client.config.RequestConfig", null)) { - setRequestFactory( + restTemplate.setRequestFactory( new CustomHttpComponentsClientHttpRequestFactory(httpClientOptions)); } - addAuthentication(username, password); - setErrorHandler(new DefaultResponseErrorHandler() { - @Override - public void handleError(ClientHttpResponse response) throws IOException { - } - }); + addAuthentication(restTemplate, username, password); + restTemplate.setErrorHandler(new NoOpResponseErrorHandler()); + return restTemplate; + } + public TestRestTemplate(RestTemplate restTemplate) { + Assert.notNull(restTemplate, "RestTemplate must not be null"); + this.restTemplate = restTemplate; } - private void addAuthentication(String username, String password) { + private void addAuthentication(RestTemplate restTemplate, String username, + String password) { if (username == null) { return; } List interceptors = Collections .singletonList( new BasicAuthorizationInterceptor(username, password)); - setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(), - interceptors)); + restTemplate.setRequestFactory(new InterceptingClientHttpRequestFactory( + restTemplate.getRequestFactory(), interceptors)); + } + + /** + * Configure the {@link UriTemplateHandler} to use to expand URI templates. By default + * the {@link DefaultUriTemplateHandler} is used which relies on Spring's URI template + * support and exposes several useful properties that customize its behavior for + * encoding and for prepending a common base URL. An alternative implementation may be + * used to plug an external URI template library. + * @param handler the URI template handler to use + */ + public void setUriTemplateHandler(UriTemplateHandler handler) { + this.restTemplate.setUriTemplateHandler(handler); + } + + /** + * Retrieve a representation by doing a GET on the specified URL. The response (if + * any) is converted and returned. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param responseType the type of the return value + * @param urlVariables the variables to expand the template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error on-client side HTTP error + * @see RestTemplate#getForObject(String, Class, Object...) + */ + public T getForObject(String url, Class responseType, Object... urlVariables) + throws RestClientException { + return this.restTemplate.getForObject(url, responseType, urlVariables); + } + + /** + * Retrieve a representation by doing a GET on the URI template. The response (if any) + * is converted and returned. + *

+ * URI Template variables are expanded using the given map. + * @param url the URL + * @param responseType the type of the return value + * @param urlVariables the map containing variables for the URI template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#getForObject(String, Class, Object...) + */ + public T getForObject(String url, Class responseType, + Map urlVariables) throws RestClientException { + return this.restTemplate.getForObject(url, responseType, urlVariables); + } + + /** + * Retrieve a representation by doing a GET on the URL . The response (if any) is + * converted and returned. + * @param url the URL + * @param responseType the type of the return value + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#getForObject(java.net.URI, java.lang.Class) + */ + public T getForObject(URI url, Class responseType) throws RestClientException { + return this.restTemplate.getForObject(url, responseType); + } + + /** + * Retrieve an entity by doing a GET on the specified URL. The response is converted + * and stored in an {@link ResponseEntity}. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param responseType the type of the return value + * @param urlVariables the variables to expand the template + * @param the type of the return value + * @return the entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, + * java.lang.Object[]) + */ + public ResponseEntity getForEntity(String url, Class responseType, + Object... urlVariables) throws RestClientException { + return this.restTemplate.getForEntity(url, responseType, urlVariables); + } + + /** + * Retrieve a representation by doing a GET on the URI template. The response is + * converted and stored in an {@link ResponseEntity}. + *

+ * URI Template variables are expanded using the given map. + * @param url the URL + * @param responseType the type of the return value + * @param urlVariables the map containing variables for the URI template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#getForEntity(java.lang.String, java.lang.Class, java.util.Map) + */ + public ResponseEntity getForEntity(String url, Class responseType, + Map urlVariables) throws RestClientException { + return this.restTemplate.getForEntity(url, responseType, urlVariables); + } + + /** + * Retrieve a representation by doing a GET on the URL . The response is converted and + * stored in an {@link ResponseEntity}. + * @param url the URL + * @param responseType the type of the return value + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#getForEntity(java.net.URI, java.lang.Class) + */ + public ResponseEntity getForEntity(URI url, Class responseType) + throws RestClientException { + return this.restTemplate.getForEntity(url, responseType); + } + + /** + * Retrieve all headers of the resource specified by the URI template. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param urlVariables the variables to expand the template + * @return all HTTP headers of that resource + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#headForHeaders(java.lang.String, java.lang.Object[]) + */ + public HttpHeaders headForHeaders(String url, Object... urlVariables) + throws RestClientException { + return this.restTemplate.headForHeaders(url, urlVariables); + } + + /** + * Retrieve all headers of the resource specified by the URI template. + *

+ * URI Template variables are expanded using the given map. + * @param url the URL + * @param urlVariables the map containing variables for the URI template + * @return all HTTP headers of that resource + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#headForHeaders(java.lang.String, java.util.Map) + */ + public HttpHeaders headForHeaders(String url, Map urlVariables) + throws RestClientException { + return this.restTemplate.headForHeaders(url, urlVariables); + } + + /** + * Retrieve all headers of the resource specified by the URL. + * @param url the URL + * @return all HTTP headers of that resource + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#headForHeaders(java.net.URI) + */ + public HttpHeaders headForHeaders(URI url) throws RestClientException { + return this.restTemplate.headForHeaders(url); + } + + /** + * Create a new resource by POSTing the given object to the URI template, and returns + * the value of the {@code Location} header. This header typically indicates where the + * new resource is stored. + *

+ * URI Template variables are expanded using the given URI variables, if any. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param urlVariables the variables to expand the template + * @return the value for the {@code Location} header + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForLocation(java.lang.String, java.lang.Object, + * java.lang.Object[]) + */ + public URI postForLocation(String url, Object request, Object... urlVariables) + throws RestClientException { + return this.restTemplate.postForLocation(url, request, urlVariables); + } + + /** + * Create a new resource by POSTing the given object to the URI template, and returns + * the value of the {@code Location} header. This header typically indicates where the + * new resource is stored. + *

+ * URI Template variables are expanded using the given map. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param urlVariables the variables to expand the template + * @return the value for the {@code Location} header + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForLocation(java.lang.String, java.lang.Object, + * java.util.Map) + */ + public URI postForLocation(String url, Object request, Map urlVariables) + throws RestClientException { + return this.restTemplate.postForLocation(url, request, urlVariables); + } + + /** + * Create a new resource by POSTing the given object to the URL, and returns the value + * of the {@code Location} header. This header typically indicates where the new + * resource is stored. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @return the value for the {@code Location} header + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForLocation(java.net.URI, java.lang.Object) + */ + public URI postForLocation(URI url, Object request) throws RestClientException { + return this.restTemplate.postForLocation(url, request); + } + + /** + * Create a new resource by POSTing the given object to the URI template, and returns + * the representation found in the response. + *

+ * URI Template variables are expanded using the given URI variables, if any. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param responseType the type of the return value + * @param urlVariables the variables to expand the template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForObject(java.lang.String, java.lang.Object, + * java.lang.Class, java.lang.Object[]) + */ + public T postForObject(String url, Object request, Class responseType, + Object... urlVariables) throws RestClientException { + return this.restTemplate.postForObject(url, request, responseType, urlVariables); + } + + /** + * Create a new resource by POSTing the given object to the URI template, and returns + * the representation found in the response. + *

+ * URI Template variables are expanded using the given map. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param responseType the type of the return value + * @param urlVariables the variables to expand the template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForObject(java.lang.String, java.lang.Object, + * java.lang.Class, java.util.Map) + */ + public T postForObject(String url, Object request, Class responseType, + Map urlVariables) throws RestClientException { + return this.restTemplate.postForObject(url, request, responseType, urlVariables); + } + + /** + * Create a new resource by POSTing the given object to the URL, and returns the + * representation found in the response. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param responseType the type of the return value + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForObject(java.net.URI, java.lang.Object, java.lang.Class) + */ + public T postForObject(URI url, Object request, Class responseType) + throws RestClientException { + return this.restTemplate.postForObject(url, request, responseType); + } + + /** + * Create a new resource by POSTing the given object to the URI template, and returns + * the response as {@link ResponseEntity}. + *

+ * URI Template variables are expanded using the given URI variables, if any. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param responseType the response type to return + * @param urlVariables the variables to expand the template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForEntity(java.lang.String, java.lang.Object, + * java.lang.Class, java.lang.Object[]) + */ + public ResponseEntity postForEntity(String url, Object request, + Class responseType, Object... urlVariables) throws RestClientException { + return this.restTemplate.postForEntity(url, request, responseType, urlVariables); + } + + /** + * Create a new resource by POSTing the given object to the URI template, and returns + * the response as {@link HttpEntity}. + *

+ * URI Template variables are expanded using the given map. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param responseType the response type to return + * @param urlVariables the variables to expand the template + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForEntity(java.lang.String, java.lang.Object, + * java.lang.Class, java.util.Map) + */ + public ResponseEntity postForEntity(String url, Object request, + Class responseType, Map urlVariables) + throws RestClientException { + return this.restTemplate.postForEntity(url, request, responseType, urlVariables); + } + + /** + * Create a new resource by POSTing the given object to the URL, and returns the + * response as {@link ResponseEntity}. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be POSTed, may be {@code null} + * @param responseType the response type to return + * @param the type of the return value + * @return the converted object + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#postForEntity(java.net.URI, java.lang.Object, java.lang.Class) + */ + public ResponseEntity postForEntity(URI url, Object request, + Class responseType) throws RestClientException { + return this.restTemplate.postForEntity(url, request, responseType); + } + + /** + * Create or update a resource by PUTting the given object to the URI. + *

+ * URI Template variables are expanded using the given URI variables, if any. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be PUT, may be {@code null} + * @param urlVariables the variables to expand the template + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#put(java.lang.String, java.lang.Object, java.lang.Object[]) + */ + public void put(String url, Object request, Object... urlVariables) + throws RestClientException { + this.restTemplate.put(url, request, urlVariables); + } + + /** + * Creates a new resource by PUTting the given object to URI template. + *

+ * URI Template variables are expanded using the given map. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be PUT, may be {@code null} + * @param urlVariables the variables to expand the template + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#put(java.lang.String, java.lang.Object, java.util.Map) + */ + public void put(String url, Object request, Map urlVariables) + throws RestClientException { + this.restTemplate.put(url, request, urlVariables); + } + + /** + * Creates a new resource by PUTting the given object to URL. + *

+ * The {@code request} parameter can be a {@link HttpEntity} in order to add + * additional HTTP headers to the request. + * @param url the URL + * @param request the Object to be PUT, may be {@code null} + * @throws RestClientException on-client side HTTP error + * @see HttpEntity + * @see RestTemplate#put(java.net.URI, java.lang.Object) + */ + public void put(URI url, Object request) throws RestClientException { + this.restTemplate.put(url, request); + } + + /** + * Delete the resources at the specified URI. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param urlVariables the variables to expand in the template + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#delete(java.lang.String, java.lang.Object[]) + */ + public void delete(String url, Object... urlVariables) throws RestClientException { + this.restTemplate.delete(url, urlVariables); + } + + /** + * Delete the resources at the specified URI. + *

+ * URI Template variables are expanded using the given map. + * @param url the URL + * @param urlVariables the variables to expand the template + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#delete(java.lang.String, java.util.Map) + */ + public void delete(String url, Map urlVariables) + throws RestClientException { + this.restTemplate.delete(url, urlVariables); + } + + /** + * Delete the resources at the specified URL. + * @param url the URL + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#delete(java.net.URI) + */ + public void delete(URI url) throws RestClientException { + this.restTemplate.delete(url); + } + + /** + * Return the value of the Allow header for the given URI. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param urlVariables the variables to expand in the template + * @return the value of the allow header + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#optionsForAllow(java.lang.String, java.lang.Object[]) + */ + public Set optionsForAllow(String url, Object... urlVariables) + throws RestClientException { + return this.restTemplate.optionsForAllow(url, urlVariables); + } + + /** + * Return the value of the Allow header for the given URI. + *

+ * URI Template variables are expanded using the given map. + * @param url the URL + * @param urlVariables the variables to expand in the template + * @return the value of the allow header + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#optionsForAllow(java.lang.String, java.util.Map) + */ + public Set optionsForAllow(String url, Map urlVariables) + throws RestClientException { + return this.restTemplate.optionsForAllow(url, urlVariables); + } + + /** + * Return the value of the Allow header for the given URL. + * @param url the URL + * @return the value of the allow header + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#optionsForAllow(java.net.URI) + */ + public Set optionsForAllow(URI url) throws RestClientException { + return this.restTemplate.optionsForAllow(url); + } + + /** + * Execute the HTTP method to the given URI template, writing the given request entity + * to the request, and returns the response as {@link ResponseEntity}. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may + * be {@code null} + * @param responseType the type of the return value + * @param urlVariables the variables to expand in the template + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, + * org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object[]) + */ + public ResponseEntity exchange(String url, HttpMethod method, + HttpEntity requestEntity, Class responseType, Object... urlVariables) + throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, + urlVariables); + } + + /** + * Execute the HTTP method to the given URI template, writing the given request entity + * to the request, and returns the response as {@link ResponseEntity}. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may + * be {@code null} + * @param responseType the type of the return value + * @param urlVariables the variables to expand in the template + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, + * org.springframework.http.HttpEntity, java.lang.Class, java.util.Map) + */ + public ResponseEntity exchange(String url, HttpMethod method, + HttpEntity requestEntity, Class responseType, + Map urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, + urlVariables); + } + + /** + * Execute the HTTP method to the given URI template, writing the given request entity + * to the request, and returns the response as {@link ResponseEntity}. + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may + * be {@code null} + * @param responseType the type of the return value + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod, + * org.springframework.http.HttpEntity, java.lang.Class) + */ + public ResponseEntity exchange(URI url, HttpMethod method, + HttpEntity requestEntity, Class responseType) + throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType); + } + + /** + * Execute the HTTP method to the given URI template, writing the given request entity + * to the request, and returns the response as {@link ResponseEntity}. The given + * {@link ParameterizedTypeReference} is used to pass generic type information: + *

+	 * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {};
+	 * ResponseEntity<List<MyBean>> response = template.exchange("http://example.com",HttpMethod.GET, null, myBean);
+	 * 
+ * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may + * be {@code null} + * @param responseType the type of the return value + * @param urlVariables the variables to expand in the template + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, + * org.springframework.http.HttpEntity, + * org.springframework.core.ParameterizedTypeReference, java.lang.Object[]) + */ + public ResponseEntity exchange(String url, HttpMethod method, + HttpEntity requestEntity, ParameterizedTypeReference responseType, + Object... urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, + urlVariables); + } + + /** + * Execute the HTTP method to the given URI template, writing the given request entity + * to the request, and returns the response as {@link ResponseEntity}. The given + * {@link ParameterizedTypeReference} is used to pass generic type information: + *
+	 * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {};
+	 * ResponseEntity<List<MyBean>> response = template.exchange("http://example.com",HttpMethod.GET, null, myBean);
+	 * 
+ * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may + * be {@code null} + * @param responseType the type of the return value + * @param urlVariables the variables to expand in the template + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(java.lang.String, org.springframework.http.HttpMethod, + * org.springframework.http.HttpEntity, + * org.springframework.core.ParameterizedTypeReference, java.util.Map) + */ + public ResponseEntity exchange(String url, HttpMethod method, + HttpEntity requestEntity, ParameterizedTypeReference responseType, + Map urlVariables) throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType, + urlVariables); + } + + /** + * Execute the HTTP method to the given URI template, writing the given request entity + * to the request, and returns the response as {@link ResponseEntity}. The given + * {@link ParameterizedTypeReference} is used to pass generic type information: + *
+	 * ParameterizedTypeReference<List<MyBean>> myBean = new ParameterizedTypeReference<List<MyBean>>() {};
+	 * ResponseEntity<List<MyBean>> response = template.exchange("http://example.com",HttpMethod.GET, null, myBean);
+	 * 
+ * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestEntity the entity (headers and/or body) to write to the request, may + * be {@code null} + * @param responseType the type of the return value + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(java.net.URI, org.springframework.http.HttpMethod, + * org.springframework.http.HttpEntity, + * org.springframework.core.ParameterizedTypeReference) + */ + public ResponseEntity exchange(URI url, HttpMethod method, + HttpEntity requestEntity, ParameterizedTypeReference responseType) + throws RestClientException { + return this.restTemplate.exchange(url, method, requestEntity, responseType); + } + + /** + * Execute the request specified in the given {@link RequestEntity} and return the + * response as {@link ResponseEntity}. Typically used in combination with the static + * builder methods on {@code RequestEntity}, for instance:
+	 * MyRequest body = ...
+	 * RequestEntity request = RequestEntity.post(new URI("http://example.com/foo")).accept(MediaType.APPLICATION_JSON).body(body);
+	 * ResponseEntity<MyResponse> response = template.exchange(request, MyResponse.class);
+	 * 
+ * @param requestEntity the entity to write to the request + * @param responseType the type of the return value + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(org.springframework.http.RequestEntity, java.lang.Class) + */ + public ResponseEntity exchange(RequestEntity requestEntity, + Class responseType) throws RestClientException { + return this.restTemplate.exchange(requestEntity, responseType); + } + + /** + * Execute the request specified in the given {@link RequestEntity} and return the + * response as {@link ResponseEntity}. The given {@link ParameterizedTypeReference} is + * used to pass generic type information:
+	 * MyRequest body = ...
+	 * RequestEntity request = RequestEntity.post(new URI("http://example.com/foo")).accept(MediaType.APPLICATION_JSON).body(body);
+	 * ParameterizedTypeReference<List<MyResponse>> myBean = new ParameterizedTypeReference<List<MyResponse>>() {};
+	 * ResponseEntity<List<MyResponse>> response = template.exchange(request, myBean);
+	 * 
+ * @param requestEntity the entity to write to the request + * @param responseType the type of the return value + * @param the type of the return value + * @return the response as entity + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#exchange(org.springframework.http.RequestEntity, + * org.springframework.core.ParameterizedTypeReference) + */ + public ResponseEntity exchange(RequestEntity requestEntity, + ParameterizedTypeReference responseType) throws RestClientException { + return this.restTemplate.exchange(requestEntity, responseType); + } + + /** + * Execute the HTTP method to the given URI template, preparing the request with the + * {@link RequestCallback}, and reading the response with a {@link ResponseExtractor}. + *

+ * URI Template variables are expanded using the given URI variables, if any. + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestCallback object that prepares the request + * @param responseExtractor object that extracts the return value from the response + * @param urlVariables the variables to expand in the template + * @param the type of the return value + * @return an arbitrary object, as returned by the {@link ResponseExtractor} + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, + * org.springframework.web.client.RequestCallback, + * org.springframework.web.client.ResponseExtractor, java.lang.Object[]) + */ + public T execute(String url, HttpMethod method, RequestCallback requestCallback, + ResponseExtractor responseExtractor, Object... urlVariables) + throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor, + urlVariables); + } + + /** + * Execute the HTTP method to the given URI template, preparing the request with the + * {@link RequestCallback}, and reading the response with a {@link ResponseExtractor}. + *

+ * URI Template variables are expanded using the given URI variables map. + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestCallback object that prepares the request + * @param responseExtractor object that extracts the return value from the response + * @param urlVariables the variables to expand in the template + * @param the type of the return value + * @return an arbitrary object, as returned by the {@link ResponseExtractor} + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, + * org.springframework.web.client.RequestCallback, + * org.springframework.web.client.ResponseExtractor, java.util.Map) + */ + public T execute(String url, HttpMethod method, RequestCallback requestCallback, + ResponseExtractor responseExtractor, Map urlVariables) + throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor, + urlVariables); + } + + /** + * Execute the HTTP method to the given URL, preparing the request with the + * {@link RequestCallback}, and reading the response with a {@link ResponseExtractor}. + * @param url the URL + * @param method the HTTP method (GET, POST, etc) + * @param requestCallback object that prepares the request + * @param responseExtractor object that extracts the return value from the response + * @param the type of the return value + * @return an arbitrary object, as returned by the {@link ResponseExtractor} + * @throws RestClientException on-client side HTTP error + * @see RestTemplate#execute(java.net.URI, org.springframework.http.HttpMethod, + * org.springframework.web.client.RequestCallback, + * org.springframework.web.client.ResponseExtractor) + */ + public T execute(URI url, HttpMethod method, RequestCallback requestCallback, + ResponseExtractor responseExtractor) throws RestClientException { + return this.restTemplate.execute(url, method, requestCallback, responseExtractor); + } + + /** + * Returns the underlying {@link RestTemplate} that is actually used to perform the + * REST operations. + * @return the restTemplate + */ + public RestTemplate getRestTemplate() { + return this.restTemplate; } /** @@ -110,7 +903,12 @@ public class TestRestTemplate extends RestTemplate { /** * Enable redirects. */ - ENABLE_REDIRECTS + ENABLE_REDIRECTS, + + /** + * Use a {@link SSLConnectionSocketFactory} with {@link TrustSelfSignedStrategy}. + */ + SSL } @@ -154,6 +952,22 @@ public class TestRestTemplate extends RestTemplate { this.cookieSpec = (options.contains(HttpClientOption.ENABLE_COOKIES) ? CookieSpecs.STANDARD : CookieSpecs.IGNORE_COOKIES); this.enableRedirects = options.contains(HttpClientOption.ENABLE_REDIRECTS); + if (options.contains(HttpClientOption.SSL)) { + setHttpClient(createSslHttpClient()); + } + } + + private HttpClient createSslHttpClient() { + try { + SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( + new SSLContextBuilder() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build()); + return HttpClients.custom().setSSLSocketFactory(socketFactory).build(); + } + catch (Exception ex) { + throw new IllegalStateException("Unable to create SSL HttpClient", ex); + } } @Override @@ -172,4 +986,12 @@ public class TestRestTemplate extends RestTemplate { } + private static class NoOpResponseErrorHandler extends DefaultResponseErrorHandler { + + @Override + public void handleError(ClientHttpResponse response) throws IOException { + } + + } + } diff --git a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java index 4200dcd1b6..80b0fa2e09 100644 --- a/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java +++ b/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/TestRestTemplateTests.java @@ -16,15 +16,24 @@ package org.springframework.boot.test.web.client; +import java.lang.reflect.Method; +import java.net.URI; + import org.apache.http.client.config.RequestConfig; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate.CustomHttpComponentsClientHttpRequestFactory; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; +import org.springframework.http.HttpMethod; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.InterceptingClientHttpRequestFactory; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.ReflectionUtils.MethodCallback; +import org.springframework.web.client.RestOperations; +import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; /** * Tests for {@link TestRestTemplate}. @@ -37,14 +46,15 @@ public class TestRestTemplateTests { @Test public void simple() { // The Apache client is on the classpath so we get the fully-fledged factory - assertThat(new TestRestTemplate().getRequestFactory()) + assertThat(new TestRestTemplate().getRestTemplate().getRequestFactory()) .isInstanceOf(HttpComponentsClientHttpRequestFactory.class); } @Test public void authenticated() { - assertThat(new TestRestTemplate("user", "password").getRequestFactory()) - .isInstanceOf(InterceptingClientHttpRequestFactory.class); + assertThat(new TestRestTemplate("user", "password").getRestTemplate() + .getRequestFactory()) + .isInstanceOf(InterceptingClientHttpRequestFactory.class); } @Test @@ -52,9 +62,59 @@ public class TestRestTemplateTests { TestRestTemplate template = new TestRestTemplate( HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template - .getRequestFactory(); + .getRestTemplate().getRequestFactory(); RequestConfig config = factory.getRequestConfig(); assertThat(config.isRedirectsEnabled()).isTrue(); } + @Test + public void restOperationsAreAvailable() throws Exception { + RestTemplate delegate = mock(RestTemplate.class); + final TestRestTemplate restTemplate = new TestRestTemplate(delegate); + ReflectionUtils.doWithMethods(RestOperations.class, new MethodCallback() { + + @Override + public void doWith(Method method) + throws IllegalArgumentException, IllegalAccessException { + Method equivalent = ReflectionUtils.findMethod(TestRestTemplate.class, + method.getName(), method.getParameterTypes()); + try { + equivalent.invoke(restTemplate, + mockArguments(method.getParameterTypes())); + } + catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private Object[] mockArguments(Class[] parameterTypes) throws Exception { + Object[] arguments = new Object[parameterTypes.length]; + for (int i = 0; i < parameterTypes.length; i++) { + arguments[i] = mockArgument(parameterTypes[i]); + } + return arguments; + } + + private Object mockArgument(Class type) throws Exception { + if (String.class.equals(type)) { + return "String"; + } + if (Object[].class.equals(type)) { + return new Object[0]; + } + if (URI.class.equals(type)) { + return new URI("http://localhost"); + } + if (HttpMethod.class.equals(type)) { + return HttpMethod.GET; + } + if (Class.class.equals(type)) { + return Object.class; + } + return mock(type); + } + + }); + + } }