[BAEL-8496] - Moved articles to their own spring-resttemplate module

This commit is contained in:
amit2103
2018-08-26 23:24:46 +05:30
parent 5bfa6d8903
commit 39f9392a0a
26 changed files with 411 additions and 185 deletions

13
spring-resttemplate/.gitignore vendored Normal file
View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1,10 @@
## Spring REST Example Project
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Spring RestTemplate Tutorial](http://www.baeldung.com/rest-template)
- [Exploring the Spring Boot TestRestTemplate](http://www.baeldung.com/spring-boot-testresttemplate)
- [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling)
- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder)

297
spring-resttemplate/pom.xml Normal file
View File

@@ -0,0 +1,297 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-resttemplate</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-resttemplate</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>
<!-- Spring Boot Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<!-- util -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<!-- okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${com.squareup.okhttp3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>
<build>
<finalName>spring-resttemplate</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<!--<wait>true</wait> caused errors on commit -->
<container>
<containerId>tomcat8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
<systemPropertyVariables>
<webTarget>cargo</webTarget>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<xstream.version>1.4.9</xstream.version>
<!-- util -->
<guava.version>20.0</guava.version>
<!-- Maven plugins -->
<cargo-maven2-plugin.version>1.6.0</cargo-maven2-plugin.version>
<findbugs-maven-plugin.version>3.0.4</findbugs-maven-plugin.version>
<!-- okhttp -->
<com.squareup.okhttp3.version>3.4.1</com.squareup.okhttp3.version>
</properties>
</project>

View File

@@ -0,0 +1,32 @@
package org.baeldung.resttemplate.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
/**
* interceptor to log incoming requests
*/
public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
logRequestDetails(request);
return execution.execute(request, body);
}
private void logRequestDetails(HttpRequest request) {
LOGGER.info("Request Headers: {}", request.getHeaders());
LOGGER.info("Request Method: {}", request.getMethod());
LOGGER.info("Request URI: {}", request.getURI());
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.resttemplate.configuration;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.web.client.RestTemplate;
/**
* customize rest template with an interceptor
*/
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
}
}

View File

@@ -0,0 +1,37 @@
package org.baeldung.resttemplate.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Controller to test RestTemplate configuration
*/
@RestController
public class HelloController {
private static final String RESOURCE_URL = "http://localhost:8082/spring-rest/baz";
private RestTemplate restTemplate;
@Autowired
public HelloController(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
@RequestMapping("/foo")
public String foo() {
ResponseEntity<String> response = restTemplate.getForEntity(RESOURCE_URL, String.class);
return response.getBody();
}
@RequestMapping("/baz")
public String baz() {
return "Foo";
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.resttemplate.configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
public class RestTemplateConfigurationApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
}
}

View File

@@ -0,0 +1,28 @@
package org.baeldung.resttemplate.configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
@Configuration
@EnableAutoConfiguration
@ComponentScan("org.baeldung.resttemplate.configuration")
public class SpringConfig {
@Bean
@Qualifier("customRestTemplateCustomizer")
public CustomRestTemplateCustomizer customRestTemplateCustomizer() {
return new CustomRestTemplateCustomizer();
}
@Bean
@DependsOn(value = {"customRestTemplateCustomizer"})
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder(customRestTemplateCustomizer());
}
}

View File

@@ -0,0 +1,45 @@
package org.baeldung.web.dto;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("Foo")
public class Foo {
private long id;
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public Foo(final long id, final String name) {
super();
this.id = id;
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,4 @@
package org.baeldung.web.exception;
public class NotFoundException extends RuntimeException {
}

View File

@@ -0,0 +1,43 @@
package org.baeldung.web.handler;
import org.baeldung.web.exception.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;
@Component
public class RestTemplateResponseErrorHandler
implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse httpResponse)
throws IOException {
return (httpResponse
.getStatusCode()
.series() == HttpStatus.Series.CLIENT_ERROR || httpResponse
.getStatusCode()
.series() == HttpStatus.Series.SERVER_ERROR);
}
@Override
public void handleError(ClientHttpResponse httpResponse)
throws IOException {
if (httpResponse
.getStatusCode()
.series() == HttpStatus.Series.SERVER_ERROR) {
//Handle SERVER_ERROR
} else if (httpResponse
.getStatusCode()
.series() == HttpStatus.Series.CLIENT_ERROR) {
//Handle CLIENT_ERROR
if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new NotFoundException();
}
}
}
}

View File

@@ -0,0 +1,22 @@
package org.baeldung.web.model;
public class Bar {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,26 @@
package org.baeldung.web.service;
import org.baeldung.web.handler.RestTemplateResponseErrorHandler;
import org.baeldung.web.model.Bar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class BarConsumerService {
private RestTemplate restTemplate;
@Autowired
public BarConsumerService(RestTemplateBuilder restTemplateBuilder) {
RestTemplate restTemplate = restTemplateBuilder
.errorHandler(new RestTemplateResponseErrorHandler())
.build();
}
public Bar fetchBarById(String barId) {
return restTemplate.getForObject("/bars/4242", Bar.class);
}
}

View File

@@ -0,0 +1,2 @@
server.port=8082
server.servlet.context-path=/spring-rest

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter">
<level value="DEBUG" />
</logger>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,5 @@
package org.baeldung.client;
public interface Consts {
int APPLICATION_PORT = 8082;
}

View File

@@ -0,0 +1,251 @@
package org.baeldung.client;
import static org.apache.commons.codec.binary.Base64.encodeBase64;
import static org.baeldung.client.Consts.APPLICATION_PORT;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Set;
import org.baeldung.web.dto.Foo;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
public class RestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String fooResourceUrl = "http://localhost:" + APPLICATION_PORT + "/spring-rest/foos";
@Before
public void beforeTest() {
restTemplate = new RestTemplate();
// restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
}
// GET
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenStatusOk() throws IOException {
final ResponseEntity<Foo> response = restTemplate.getForEntity(fooResourceUrl + "/1", Foo.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenResourceUrl_whenSendGetForRequestEntity_thenBodyCorrect() throws IOException {
final RestTemplate template = new RestTemplate();
final ResponseEntity<String> response = template.getForEntity(fooResourceUrl + "/1", String.class);
final ObjectMapper mapper = new ObjectMapper();
final JsonNode root = mapper.readTree(response.getBody());
final JsonNode name = root.path("name");
assertThat(name.asText(), notNullValue());
}
@Test
public void givenResourceUrl_whenRetrievingResource_thenCorrect() throws IOException {
final Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class);
assertThat(foo.getName(), notNullValue());
assertThat(foo.getId(), is(1L));
}
// HEAD, OPTIONS
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeadersForThatResource() {
final HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
assertTrue(httpHeaders.getContentType()
.includes(MediaType.APPLICATION_JSON));
}
// POST
@Test
public void givenFooService_whenPostForObject_thenCreatedObjectIsReturned() {
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
final Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
}
@Test
public void givenFooService_whenPostForLocation_thenCreatedLocationIsReturned() {
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
final URI location = restTemplate.postForLocation(fooResourceUrl, request);
assertThat(location, notNullValue());
}
@Test
public void givenFooService_whenPostResource_thenResourceIsCreated() {
final Foo foo = new Foo("bar");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
final Foo fooResponse = response.getBody();
assertThat(fooResponse, notNullValue());
assertThat(fooResponse.getName(), is("bar"));
}
@Test
public void givenFooService_whenCallOptionsForAllow_thenReceiveValueOfAllowHeader() {
final Set<HttpMethod> optionsForAllow = restTemplate.optionsForAllow(fooResourceUrl);
final HttpMethod[] supportedMethods = { HttpMethod.GET, HttpMethod.POST, HttpMethod.HEAD };
assertTrue(optionsForAllow.containsAll(Arrays.asList(supportedMethods)));
}
// PUT
@Test
public void givenFooService_whenPutExistingEntity_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create Resource
final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
// Update Resource
final Foo updatedInstance = new Foo("newName");
updatedInstance.setId(createResponse.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody()
.getId();
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);
restTemplate.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
// Check that Resource was updated
final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = updateResponse.getBody();
assertThat(foo.getName(), is(updatedInstance.getName()));
}
@Test
public void givenFooService_whenPutExistingEntityWithCallback_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create entity
ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
// Update entity
final Foo updatedInstance = new Foo("newName");
updatedInstance.setId(response.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + response.getBody()
.getId();
restTemplate.execute(resourceUrl, HttpMethod.PUT, requestCallback(updatedInstance), clientHttpResponse -> null);
// Check that entity was updated
response = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = response.getBody();
assertThat(foo.getName(), is(updatedInstance.getName()));
}
// PATCH
@Test
public void givenFooService_whenPatchExistingEntity_thenItIsUpdated() {
final HttpHeaders headers = prepareBasicAuthHeaders();
final HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"), headers);
// Create Resource
final ResponseEntity<Foo> createResponse = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
// Update Resource
final Foo updatedResource = new Foo("newName");
updatedResource.setId(createResponse.getBody()
.getId());
final String resourceUrl = fooResourceUrl + '/' + createResponse.getBody()
.getId();
final HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedResource, headers);
final ClientHttpRequestFactory requestFactory = getSimpleClientHttpRequestFactory();
final RestTemplate template = new RestTemplate(requestFactory);
template.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
template.patchForObject(resourceUrl, requestUpdate, Void.class);
// Check that Resource was updated
final ResponseEntity<Foo> updateResponse = restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(headers), Foo.class);
final Foo foo = updateResponse.getBody();
assertThat(foo.getName(), is(updatedResource.getName()));
}
// DELETE
@Test
public void givenFooService_whenCallDelete_thenEntityIsRemoved() {
final Foo foo = new Foo("remove me");
final ResponseEntity<Foo> response = restTemplate.postForEntity(fooResourceUrl, foo, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
final String entityUrl = fooResourceUrl + "/" + response.getBody()
.getId();
restTemplate.delete(entityUrl);
try {
restTemplate.getForEntity(entityUrl, Foo.class);
fail();
} catch (final HttpClientErrorException ex) {
assertThat(ex.getStatusCode(), is(HttpStatus.NOT_FOUND));
}
}
//
private HttpHeaders prepareBasicAuthHeaders() {
final HttpHeaders headers = new HttpHeaders();
final String encodedLogPass = getBase64EncodedLogPass();
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + encodedLogPass);
return headers;
}
private String getBase64EncodedLogPass() {
final String logPass = "user1:user1Pass";
final byte[] authHeaderBytes = encodeBase64(logPass.getBytes(Charsets.US_ASCII));
return new String(authHeaderBytes, Charsets.US_ASCII);
}
private RequestCallback requestCallback(final Foo updatedInstance) {
return clientHttpRequest -> {
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);
clientHttpRequest.getHeaders()
.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
clientHttpRequest.getHeaders()
.add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());
};
}
// Simply setting restTemplate timeout using ClientHttpRequestFactory
ClientHttpRequestFactory getSimpleClientHttpRequestFactory() {
final int timeout = 5;
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
return clientHttpRequestFactory;
}
}

View File

@@ -0,0 +1,117 @@
package org.baeldung.client;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
public class TestRestTemplateBasicLiveTest {
private RestTemplate restTemplate;
private static final String FOO_RESOURCE_URL = "http://localhost:" + 8082 + "/spring-rest/foos";
private static final String URL_SECURED_BY_AUTHENTICATION = "http://httpbin.org/basic-auth/user/passwd";
private static final String BASE_URL = "http://localhost:" + 8082 + "/spring-rest";
@Before
public void beforeTest() {
restTemplate = new RestTemplate();
}
// GET
@Test
public void givenTestRestTemplate_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate);
ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenRestTemplateBuilderWrapper_whenSendGetForEntity_thenStatusOk() {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
restTemplateBuilder.build();
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
ResponseEntity<String> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, "user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithCredentials_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithBasicAuth_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
ResponseEntity<String> response = testRestTemplate.withBasicAuth("user", "passwd").
getForEntity(URL_SECURED_BY_AUTHENTICATION, String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
@Test
public void givenTestRestTemplateWithCredentialsAndEnabledCookies_whenSendGetForEntity_thenStatusOk() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd", TestRestTemplate.
HttpClientOption.ENABLE_COOKIES);
ResponseEntity<String> response = testRestTemplate.getForEntity(URL_SECURED_BY_AUTHENTICATION,
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
}
// HEAD
@Test
public void givenFooService_whenCallHeadForHeaders_thenReceiveAllHeaders() {
TestRestTemplate testRestTemplate = new TestRestTemplate();
final HttpHeaders httpHeaders = testRestTemplate.headForHeaders(FOO_RESOURCE_URL);
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
}
// POST
@Test
public void givenService_whenPostForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.postForObject(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
// PUT
@Test
public void givenService_whenPutForObject_thenCreatedObjectIsReturned() {
TestRestTemplate testRestTemplate = new TestRestTemplate("user", "passwd");
final RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/html; charset=utf-8"),
"{\"id\":1,\"name\":\"Jim\"}");
final Request request = new Request.Builder().url(BASE_URL + "/users/detail").post(body).build();
testRestTemplate.put(URL_SECURED_BY_AUTHENTICATION, request, String.class);
}
}

View File

@@ -0,0 +1,48 @@
package org.baeldung.web.handler;
import org.baeldung.web.exception.NotFoundException;
import org.baeldung.web.model.Bar;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
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.withStatus;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { NotFoundException.class, Bar.class })
@RestClientTest
public class RestTemplateResponseErrorHandlerIntegrationTest {
@Autowired private MockRestServiceServer server;
@Autowired private RestTemplateBuilder builder;
@Test(expected = NotFoundException.class)
public void givenRemoteApiCall_when404Error_thenThrowNotFound() {
Assert.assertNotNull(this.builder);
Assert.assertNotNull(this.server);
RestTemplate restTemplate = this.builder
.errorHandler(new RestTemplateResponseErrorHandler())
.build();
this.server
.expect(ExpectedCount.once(), requestTo("/bars/4242"))
.andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
Bar response = restTemplate.getForObject("/bars/4242", Bar.class);
this.server.verify();
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear