JAVA-3540: Move spring-resttemplate into spring-web-modules
This commit is contained in:
@@ -34,6 +34,7 @@
|
||||
<module>spring-rest-shell</module>
|
||||
<module>spring-rest-simple</module>
|
||||
<module>spring-rest-testing</module>
|
||||
<module>spring-resttemplate</module>
|
||||
<module>spring-resttemplate-2</module>
|
||||
<module>spring-thymeleaf</module>
|
||||
<module>spring-thymeleaf-2</module>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1,23 @@
|
||||
## Spring RestTemplate
|
||||
|
||||
This module contains articles about Spring RestTemplate
|
||||
|
||||
### The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Guide to RestTemplate](https://www.baeldung.com/rest-template)
|
||||
- [Exploring the Spring Boot TestRestTemplate](https://www.baeldung.com/spring-boot-testresttemplate)
|
||||
- [Spring RestTemplate Error Handling](https://www.baeldung.com/spring-rest-template-error-handling)
|
||||
- [Configure a RestTemplate with RestTemplateBuilder](https://www.baeldung.com/spring-rest-template-builder)
|
||||
- [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template)
|
||||
- [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file)
|
||||
- [Using the Spring RestTemplate Interceptor](https://www.baeldung.com/spring-rest-template-interceptor)
|
||||
- [Uploading MultipartFile with Spring RestTemplate](https://www.baeldung.com/spring-rest-template-multipart-upload)
|
||||
- [Get and Post Lists of Objects with RestTemplate](https://www.baeldung.com/spring-rest-template-list)
|
||||
- [HTTP PUT vs HTTP PATCH in a REST API](https://www.baeldung.com/http-put-patch-difference-spring)
|
||||
|
||||
### NOTE:
|
||||
|
||||
This module is closed and should **not** be used to store the code
|
||||
for any further articles.
|
||||
@@ -0,0 +1,312 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-resttemplate</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-resttemplate</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</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-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>au.com.dius</groupId>
|
||||
<artifactId>pact-jvm-provider-junit_2.11</artifactId>
|
||||
<version>${pact.version}</version>
|
||||
</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 -->
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/junit/junit -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest</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>${maven.version}</version>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${target.version}</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>
|
||||
<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>
|
||||
<pact.version>3.5.11</pact.version>
|
||||
<source.version>1.8</source.version>
|
||||
<target.version>1.8</target.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven.version>3.7.0</maven.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.responseheaders;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||
|
||||
@ServletComponentScan
|
||||
@SpringBootApplication
|
||||
public class ResponseHeadersApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ResponseHeadersApplication.class, args);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.responseheaders.controllers;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/filter-response-header")
|
||||
public class FilterResponseHeaderController {
|
||||
|
||||
@GetMapping("/no-extra-header")
|
||||
public String FilterHeaderResponseWithNoExtraHeader() {
|
||||
return "Response body with Filter header and no extra header";
|
||||
}
|
||||
|
||||
@GetMapping("/extra-header")
|
||||
public String FilterHeaderResponseWithExtraHeader(HttpServletResponse response) {
|
||||
response.addHeader("Baeldung-Example-Header", "Value-ExtraHeader");
|
||||
return "Response body with Filter header and one extra header";
|
||||
}
|
||||
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.responseheaders.controllers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/single-response-header")
|
||||
public class ResponseHeaderController {
|
||||
|
||||
@GetMapping("/http-servlet-response")
|
||||
public String usingHttpServletResponse(HttpServletResponse response) {
|
||||
response.addHeader("Baeldung-Example-Header", "Value-HttpServletResponse");
|
||||
return "Response with header using HttpServletResponse";
|
||||
}
|
||||
|
||||
@GetMapping("/response-entity-constructor")
|
||||
public ResponseEntity<String> usingResponseEntityConstructor() {
|
||||
HttpHeaders responseHeaders = new HttpHeaders();
|
||||
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityContructor");
|
||||
String responseBody = "Response with header using ResponseEntity (constructor)";
|
||||
HttpStatus responseStatus = HttpStatus.OK;
|
||||
|
||||
return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus);
|
||||
}
|
||||
|
||||
@GetMapping("/response-entity-contructor-multiple-headers")
|
||||
public ResponseEntity<String> usingResponseEntityConstructorAndMultipleHeaders() {
|
||||
List<MediaType> acceptableMediaTypes = new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON));
|
||||
HttpHeaders responseHeaders = new HttpHeaders();
|
||||
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityConstructorAndHeaders");
|
||||
responseHeaders.setAccept(acceptableMediaTypes);
|
||||
String responseBody = "Response with header using ResponseEntity (constructor)";
|
||||
HttpStatus responseStatus = HttpStatus.OK;
|
||||
|
||||
return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus);
|
||||
}
|
||||
|
||||
@GetMapping("/response-entity-builder")
|
||||
public ResponseEntity<String> usingResponseEntityBuilder() {
|
||||
String responseHeaderKey = "Baeldung-Example-Header";
|
||||
String responseHeaderValue = "Value-ResponseEntityBuilder";
|
||||
String responseBody = "Response with header using ResponseEntity (builder)";
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header(responseHeaderKey, responseHeaderValue)
|
||||
.body(responseBody);
|
||||
}
|
||||
|
||||
@GetMapping("/response-entity-builder-with-http-headers")
|
||||
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
|
||||
HttpHeaders responseHeaders = new HttpHeaders();
|
||||
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityBuilderWithHttpHeaders");
|
||||
String responseBody = "Response with header using ResponseEntity (builder)";
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(responseHeaders)
|
||||
.body(responseBody);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.responseheaders.filter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@WebFilter("/filter-response-header/*")
|
||||
public class AddResponseHeaderFilter implements Filter {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(AddResponseHeaderFilter.class);
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
// add special initialization requirements here
|
||||
LOGGER.trace("Initializing filter...");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
|
||||
httpServletResponse.setHeader("Baeldung-Example-Filter-Header", "Value-Filter");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
// clean up any resource being held by the filter here
|
||||
LOGGER.trace("Destroying filter...");
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.resttemplate;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.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());
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.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());
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.baeldung.resttemplate.configuration;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
import com.baeldung.resttemplate.web.dto.Foo;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
@Controller
|
||||
public class FooController {
|
||||
|
||||
private Map<Long, Foo> fooRepository = Maps.newHashMap(ImmutableMap.of(1L, new Foo(1L, randomAlphabetic(4))));
|
||||
|
||||
public FooController() {
|
||||
super();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/foos")
|
||||
@ResponseBody
|
||||
public Collection<Foo> findListOfFoo() {
|
||||
return fooRepository.values();
|
||||
}
|
||||
|
||||
// API - read
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/foos/{id}")
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable final long id) throws HttpClientErrorException {
|
||||
Foo foo = fooRepository.get(id);
|
||||
|
||||
if (foo == null) {
|
||||
throw new HttpClientErrorException(HttpStatus.NOT_FOUND);
|
||||
} else {
|
||||
return foo;
|
||||
}
|
||||
}
|
||||
|
||||
// API - write
|
||||
|
||||
@RequestMapping(method = RequestMethod.PUT, value = "/foos/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
fooRepository.put(id, foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/foos/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo patchFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
fooRepository.put(id, foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/foos")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public ResponseEntity<Foo> postFoo(@RequestBody final Foo foo) {
|
||||
|
||||
fooRepository.put(foo.getId(), foo);
|
||||
final URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentServletMapping()
|
||||
.path("/foos/{id}")
|
||||
.build()
|
||||
.expand(foo.getId())
|
||||
.toUri();
|
||||
|
||||
final HttpHeaders headers = new HttpHeaders();
|
||||
headers.setLocation(location);
|
||||
|
||||
final ResponseEntity<Foo> entity = new ResponseEntity<Foo>(foo, headers, HttpStatus.CREATED);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.HEAD, value = "/foos")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo headFoo() {
|
||||
return new Foo(1, randomAlphabetic(4));
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/foos/new")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo createFoo(@RequestBody final Foo foo) {
|
||||
fooRepository.put(foo.getId(), foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, value = "/foos/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public long deleteFoo(@PathVariable final long id) {
|
||||
fooRepository.remove(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, value = "/foos/form")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public String submitFoo(@RequestParam("id") String id) {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.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";
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.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;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.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());
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.resttemplate.lists;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Sample application used to demonstrate working with Lists and RestTemplate.
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class EmployeeApplication
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(EmployeeApplication.class, args);
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.resttemplate.lists.client;
|
||||
|
||||
import com.baeldung.resttemplate.lists.dto.Employee;
|
||||
import com.baeldung.resttemplate.lists.dto.EmployeeList;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
/**
|
||||
* Application that shows how to use Lists with RestTemplate.
|
||||
*/
|
||||
public class EmployeeClient {
|
||||
public static void main(String[] args) {
|
||||
EmployeeClient employeeClient = new EmployeeClient();
|
||||
|
||||
System.out.println("Calling GET for entity using arrays");
|
||||
employeeClient.getForEntityEmployeesAsArray();
|
||||
|
||||
System.out.println("Calling GET using ParameterizedTypeReference");
|
||||
employeeClient.getAllEmployeesUsingParameterizedTypeReference();
|
||||
|
||||
System.out.println("Calling GET using wrapper class");
|
||||
employeeClient.getAllEmployeesUsingWrapperClass();
|
||||
|
||||
System.out.println("Calling POST using normal lists");
|
||||
employeeClient.createEmployeesUsingLists();
|
||||
|
||||
System.out.println("Calling POST using wrapper class");
|
||||
employeeClient.createEmployeesUsingWrapperClass();
|
||||
}
|
||||
|
||||
public EmployeeClient() {
|
||||
|
||||
}
|
||||
|
||||
public Employee[] getForEntityEmployeesAsArray() {
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
ResponseEntity<Employee[]> response =
|
||||
restTemplate.getForEntity(
|
||||
"http://localhost:8082/spring-rest/employees/",
|
||||
Employee[].class);
|
||||
|
||||
Employee[] employees = response.getBody();
|
||||
|
||||
assert employees != null;
|
||||
asList(employees).forEach(System.out::println);
|
||||
|
||||
return employees;
|
||||
|
||||
}
|
||||
|
||||
|
||||
public List<Employee> getAllEmployeesUsingParameterizedTypeReference() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
ResponseEntity<List<Employee>> response =
|
||||
restTemplate.exchange(
|
||||
"http://localhost:8082/spring-rest/employees/",
|
||||
HttpMethod.GET,
|
||||
null,
|
||||
new ParameterizedTypeReference<List<Employee>>() {
|
||||
});
|
||||
|
||||
List<Employee> employees = response.getBody();
|
||||
|
||||
assert employees != null;
|
||||
employees.forEach(System.out::println);
|
||||
|
||||
return employees;
|
||||
}
|
||||
|
||||
public List<Employee> getAllEmployeesUsingWrapperClass() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
EmployeeList response =
|
||||
restTemplate.getForObject(
|
||||
"http://localhost:8082/spring-rest/employees/v2",
|
||||
EmployeeList.class);
|
||||
|
||||
List<Employee> employees = response.getEmployees();
|
||||
|
||||
employees.forEach(System.out::println);
|
||||
|
||||
return employees;
|
||||
}
|
||||
|
||||
public void createEmployeesUsingLists() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
List<Employee> newEmployees = new ArrayList<>();
|
||||
newEmployees.add(new Employee(3, "Intern"));
|
||||
newEmployees.add(new Employee(4, "CEO"));
|
||||
|
||||
restTemplate.postForObject(
|
||||
"http://localhost:8082/spring-rest/employees/",
|
||||
newEmployees,
|
||||
ResponseEntity.class);
|
||||
}
|
||||
|
||||
public void createEmployeesUsingWrapperClass() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
List<Employee> newEmployees = new ArrayList<>();
|
||||
newEmployees.add(new Employee(3, "Intern"));
|
||||
newEmployees.add(new Employee(4, "CEO"));
|
||||
|
||||
restTemplate.postForObject(
|
||||
"http://localhost:8082/spring-rest/employees/v2/",
|
||||
new EmployeeList(newEmployees),
|
||||
ResponseEntity.class);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.resttemplate.lists.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.resttemplate.lists.dto.Employee;
|
||||
import com.baeldung.resttemplate.lists.dto.EmployeeList;
|
||||
import com.baeldung.resttemplate.lists.service.EmployeeService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/employees")
|
||||
public class EmployeeResource
|
||||
{
|
||||
@Autowired
|
||||
private EmployeeService employeeService;
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/")
|
||||
public List<Employee> getEmployees()
|
||||
{
|
||||
return employeeService.getAllEmployees();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, path = "/v2")
|
||||
public EmployeeList getEmployeesUsingWrapperClass()
|
||||
{
|
||||
List<Employee> employees = employeeService.getAllEmployees();
|
||||
return new EmployeeList(employees);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/")
|
||||
public void addEmployees(@RequestBody List<Employee> employees)
|
||||
{
|
||||
employeeService.addEmployees(employees);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, path = "/v2")
|
||||
public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper)
|
||||
{
|
||||
employeeService.addEmployees(employeeWrapper.getEmployees());
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.resttemplate.lists.dto;
|
||||
|
||||
public class Employee {
|
||||
|
||||
public long id;
|
||||
public String title;
|
||||
|
||||
public Employee()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Employee(long id, String title)
|
||||
{
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return "Employee #" + id + "[" + title + "]";
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.resttemplate.lists.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class EmployeeList
|
||||
{
|
||||
public List<Employee> employees;
|
||||
|
||||
public EmployeeList()
|
||||
{
|
||||
employees = new ArrayList<>();
|
||||
}
|
||||
|
||||
public EmployeeList(List<Employee> employees)
|
||||
{
|
||||
this.employees = employees;
|
||||
}
|
||||
|
||||
public void setEmployees(List<Employee> employees)
|
||||
{
|
||||
this.employees = employees;
|
||||
}
|
||||
|
||||
public List<Employee> getEmployees()
|
||||
{
|
||||
return employees;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.resttemplate.lists.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.resttemplate.lists.dto.Employee;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service("EmployeeListService")
|
||||
public class EmployeeService
|
||||
{
|
||||
public List<Employee> getAllEmployees()
|
||||
{
|
||||
List<Employee> employees = new ArrayList<>();
|
||||
employees.add(new Employee(1, "Manager"));
|
||||
employees.add(new Employee(2, "Java Developer"));
|
||||
return employees;
|
||||
}
|
||||
|
||||
public void addEmployees(List<Employee> employees)
|
||||
{
|
||||
employees.forEach(e -> System.out.println("Adding new employee " + e));
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.resttemplate.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;
|
||||
}
|
||||
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.resttemplate.web.exception;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.resttemplate.web.handler;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.resttemplate.web.exception.NotFoundException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.ResponseErrorHandler;
|
||||
|
||||
@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
|
||||
throw new HttpClientErrorException(httpResponse.getStatusCode());
|
||||
} else if (httpResponse
|
||||
.getStatusCode()
|
||||
.series() == HttpStatus.Series.CLIENT_ERROR) {
|
||||
//Handle CLIENT_ERROR
|
||||
if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.resttemplate.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;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.resttemplate.web.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
|
||||
public Employee(String id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Employee employee = (Employee) o;
|
||||
return Objects.equals(id, employee.id);
|
||||
}
|
||||
|
||||
@Override public int hashCode() {
|
||||
|
||||
return Objects.hash(id);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.resttemplate.web.service;
|
||||
|
||||
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
|
||||
import com.baeldung.resttemplate.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 = restTemplateBuilder
|
||||
.errorHandler(new RestTemplateResponseErrorHandler())
|
||||
.build();
|
||||
}
|
||||
|
||||
public Bar fetchBarById(String barId) {
|
||||
return restTemplate.getForObject("/bars/4242", Bar.class);
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.resttemplate.web.service;
|
||||
|
||||
import com.baeldung.resttemplate.web.model.Employee;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Service
|
||||
public class EmployeeService {
|
||||
|
||||
static final String EMP_URL_PREFIX = "http://localhost:8080/employee";
|
||||
static final String URL_SEP = "/";
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);
|
||||
|
||||
@Autowired
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
public Employee getEmployee(String id) {
|
||||
|
||||
ResponseEntity<Employee> resp = restTemplate.getForEntity("http://localhost:8080/employee/" + id,
|
||||
Employee.class);
|
||||
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.sampleapp.config;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung.sampleapp")
|
||||
public class MainApplication implements WebMvcConfigurer {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(MainApplication.class, args);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.sampleapp.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.sampleapp.interceptors.RestTemplateHeaderModifierInterceptor;
|
||||
|
||||
@Configuration
|
||||
public class RestClientConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
|
||||
if (CollectionUtils.isEmpty(interceptors)) {
|
||||
interceptors = new ArrayList<ClientHttpRequestInterceptor>();
|
||||
}
|
||||
interceptors.add(new RestTemplateHeaderModifierInterceptor());
|
||||
restTemplate.setInterceptors(interceptors);
|
||||
return restTemplate;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.sampleapp.config;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/*
|
||||
* Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan({ "com.baeldung.sampleapp.web" })
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
public WebConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
/*
|
||||
@Override
|
||||
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
|
||||
final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
|
||||
builder.indentOutput(true)
|
||||
.dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
|
||||
messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
|
||||
// messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
|
||||
|
||||
// messageConverters.add(new MappingJackson2HttpMessageConverter());
|
||||
|
||||
// messageConverters.add(new ProtobufHttpMessageConverter());
|
||||
|
||||
}
|
||||
|
||||
*/
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.sampleapp.interceptors;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.springframework.http.HttpRequest;
|
||||
import org.springframework.http.client.ClientHttpRequestExecution;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
|
||||
public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor {
|
||||
|
||||
@Override
|
||||
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
|
||||
ClientHttpResponse response = execution.execute(request, body);
|
||||
response.getHeaders().add("Foo", "bar");
|
||||
return response;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.sampleapp.repository;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResource;
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
|
||||
|
||||
public class HeavyResourceRepository {
|
||||
|
||||
public void save(HeavyResource heavyResource) {
|
||||
}
|
||||
|
||||
public void save(HeavyResourceAddressOnly partialUpdate) {
|
||||
|
||||
}
|
||||
|
||||
public void save(Map<String, Object> updates, String id) {
|
||||
|
||||
}
|
||||
|
||||
public void save(HeavyResource heavyResource, String id) {
|
||||
|
||||
}
|
||||
|
||||
public void save(HeavyResourceAddressOnly partialUpdate, String id) {
|
||||
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/ex")
|
||||
public class BarMappingExamplesController {
|
||||
|
||||
public BarMappingExamplesController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// with @RequestParam
|
||||
|
||||
@RequestMapping(value = "/bars")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = "id")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = { "id", "second" })
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
// with @PathVariable
|
||||
|
||||
@RequestMapping(value = "/bars/{numericId:[\\d]+}")
|
||||
@ResponseBody
|
||||
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
|
||||
return "Get a specific Bar with id=" + numericId;
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Company;
|
||||
|
||||
@RestController
|
||||
public class CompanyController {
|
||||
|
||||
@RequestMapping(value = "/companyRest", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public Company getCompanyRest() {
|
||||
final Company company = new Company(1, "Xpto");
|
||||
return company;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.request.async.DeferredResult;
|
||||
|
||||
@RestController
|
||||
public class DeferredResultController {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
|
||||
|
||||
@GetMapping("/async-deferredresult")
|
||||
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
|
||||
LOG.info("Received request");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
|
||||
|
||||
deferredResult.onCompletion(() -> LOG.info("Processing complete"));
|
||||
|
||||
CompletableFuture.supplyAsync(() -> {
|
||||
LOG.info("Processing in separate thread");
|
||||
try {
|
||||
Thread.sleep(6000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "OK";
|
||||
})
|
||||
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
|
||||
|
||||
LOG.info("Servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
@GetMapping("/process-blocking")
|
||||
public ResponseEntity<?> handleReqSync(Model model) {
|
||||
// ...
|
||||
return ResponseEntity.ok("ok");
|
||||
}
|
||||
|
||||
@GetMapping("/async-deferredresult-timeout")
|
||||
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
|
||||
LOG.info("Received async request with a configured timeout");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
|
||||
deferredResult.onTimeout(() -> deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT)
|
||||
.body("Request timeout occurred.")));
|
||||
|
||||
CompletableFuture.supplyAsync(() -> {
|
||||
LOG.info("Processing in separate thread");
|
||||
try {
|
||||
Thread.sleep(6000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "error";
|
||||
})
|
||||
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
|
||||
LOG.info("servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
@GetMapping("/async-deferredresult-error")
|
||||
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
|
||||
LOG.info("Received async request with a configured error handler");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
|
||||
deferredResult.onError(new Consumer<Throwable>() {
|
||||
@Override
|
||||
public void accept(Throwable t) {
|
||||
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("An error occurred."));
|
||||
}
|
||||
|
||||
});
|
||||
LOG.info("servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.repository.HeavyResourceRepository;
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResource;
|
||||
import com.baeldung.sampleapp.web.dto.HeavyResourceAddressOnly;
|
||||
|
||||
@RestController
|
||||
public class HeavyResourceController {
|
||||
|
||||
private HeavyResourceRepository heavyResourceRepository = new HeavyResourceRepository();
|
||||
|
||||
@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> saveResource(@RequestBody HeavyResource heavyResource, @PathVariable("id") String id) {
|
||||
heavyResourceRepository.save(heavyResource, id);
|
||||
return ResponseEntity.ok("resource saved");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/heavyresource/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> partialUpdateName(@RequestBody HeavyResourceAddressOnly partialUpdate, @PathVariable("id") String id) {
|
||||
heavyResourceRepository.save(partialUpdate, id);
|
||||
return ResponseEntity.ok("resource address updated");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/heavyresource2/{id}", method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<?> partialUpdateGeneric(@RequestBody Map<String, Object> updates,
|
||||
@PathVariable("id") String id) {
|
||||
heavyResourceRepository.save(updates, id);
|
||||
return ResponseEntity.ok("resource updated");
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Item;
|
||||
import com.baeldung.sampleapp.web.dto.ItemManager;
|
||||
import com.baeldung.sampleapp.web.dto.Views;
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
@RestController
|
||||
public class ItemController {
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
@RequestMapping("/items/{id}")
|
||||
public Item getItemPublic(@PathVariable final int id) {
|
||||
return ItemManager.getById(id);
|
||||
}
|
||||
|
||||
@JsonView(Views.Internal.class)
|
||||
@RequestMapping("/items/internal/{id}")
|
||||
public Item getItemInternal(@PathVariable final int id) {
|
||||
return ItemManager.getById(id);
|
||||
}
|
||||
|
||||
@RequestMapping("/date")
|
||||
public Date getCurrentDate() throws Exception {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
@RequestMapping("/delay/{seconds}")
|
||||
public void getCurrentTime(@PathVariable final int seconds) throws Exception {
|
||||
|
||||
Thread.sleep(seconds * 1000);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Foo;
|
||||
import com.baeldung.sampleapp.web.exception.ResourceNotFoundException;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/foo")
|
||||
public class MyFooController {
|
||||
|
||||
private final Map<Long, Foo> myfoos;
|
||||
|
||||
public MyFooController() {
|
||||
super();
|
||||
myfoos = new HashMap<Long, Foo>();
|
||||
myfoos.put(1L, new Foo(1L, "sample foo"));
|
||||
}
|
||||
|
||||
// API - read
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
|
||||
@ResponseBody
|
||||
public Collection<Foo> findAll() {
|
||||
return myfoos.values();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = { "application/json" })
|
||||
@ResponseBody
|
||||
public Foo findById(@PathVariable final long id) {
|
||||
final Foo foo = myfoos.get(id);
|
||||
if (foo == null) {
|
||||
throw new ResourceNotFoundException();
|
||||
}
|
||||
return foo;
|
||||
}
|
||||
|
||||
// API - write
|
||||
|
||||
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
myfoos.put(id, foo);
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.PATCH, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void updateFoo2(@PathVariable("id") final long id, @RequestBody final Foo foo) {
|
||||
myfoos.put(id, foo);
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
@ResponseBody
|
||||
public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) {
|
||||
myfoos.put(foo.getId(), foo);
|
||||
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest()
|
||||
.path("/" + foo.getId())
|
||||
.toUriString());
|
||||
return foo;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public void deleteById(@PathVariable final long id) {
|
||||
myfoos.remove(id);
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.PactDto;
|
||||
|
||||
@RestController
|
||||
public class PactController {
|
||||
|
||||
List<PactDto> pacts = new ArrayList<>();
|
||||
|
||||
@GetMapping(value = "/pact", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ResponseBody
|
||||
public PactDto getPact() {
|
||||
return new PactDto(true, "tom");
|
||||
}
|
||||
|
||||
@PostMapping("/pact")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public void createPact(PactDto pact) {
|
||||
pacts.add(pact);
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.sampleapp.web.controller;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.baeldung.sampleapp.web.dto.Foo;
|
||||
|
||||
// used to test HttpClientPostingTest
|
||||
@RestController
|
||||
public class SimplePostController {
|
||||
|
||||
@RequestMapping(value = "/users", method = RequestMethod.POST)
|
||||
public String postUser(@RequestParam final String username, @RequestParam final String password) {
|
||||
return "Success" + username;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/detail", method = RequestMethod.POST)
|
||||
public String postUserDetail(@RequestBody final Foo entity) {
|
||||
return "Success" + entity.getId();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
|
||||
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
|
||||
final String fileName = dateFormat.format(new Date());
|
||||
final File fileServer = new File(fileName);
|
||||
fileServer.createNewFile();
|
||||
final byte[] bytes = file.getBytes();
|
||||
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
|
||||
stream.write(bytes);
|
||||
stream.close();
|
||||
return "You successfully uploaded " + username;
|
||||
} catch (final Exception e) {
|
||||
return "You failed to upload " + e.getMessage();
|
||||
}
|
||||
} else {
|
||||
return "You failed to upload because the file was empty.";
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/upload", method = RequestMethod.POST)
|
||||
public String postMultipart(@RequestParam("file") final MultipartFile file) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
|
||||
final String fileName = dateFormat.format(new Date());
|
||||
final File fileServer = new File(fileName);
|
||||
fileServer.createNewFile();
|
||||
final byte[] bytes = file.getBytes();
|
||||
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
|
||||
stream.write(bytes);
|
||||
stream.close();
|
||||
return "You successfully uploaded ";
|
||||
} catch (final Exception e) {
|
||||
return "You failed to upload " + e.getMessage();
|
||||
}
|
||||
} else {
|
||||
return "You failed to upload because the file was empty.";
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.sampleapp.web.controller.redirect;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.View;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/")
|
||||
public class RedirectController {
|
||||
|
||||
@RequestMapping(value = "/redirectWithXMLConfig", method = RequestMethod.GET)
|
||||
public ModelAndView redirectWithUsingXMLConfig(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithXMLConfig");
|
||||
return new ModelAndView("RedirectedUrl", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectWithRedirectPrefix", method = RequestMethod.GET)
|
||||
public ModelAndView redirectWithUsingRedirectPrefix(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithRedirectPrefix");
|
||||
return new ModelAndView("redirect:/redirectedUrl", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectWithRedirectAttributes", method = RequestMethod.GET)
|
||||
public RedirectView redirectWithRedirectAttributes(final RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
|
||||
redirectAttributes.addAttribute("attribute", "redirectWithRedirectAttributes");
|
||||
return new RedirectView("redirectedUrl");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectWithRedirectView", method = RequestMethod.GET)
|
||||
public RedirectView redirectWithUsingRedirectView(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithRedirectView");
|
||||
return new RedirectView("redirectedUrl");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/forwardWithForwardPrefix", method = RequestMethod.GET)
|
||||
public ModelAndView forwardWithUsingForwardPrefix(final ModelMap model) {
|
||||
model.addAttribute("attribute", "redirectWithForwardPrefix");
|
||||
return new ModelAndView("forward:/redirectedUrl", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectedUrl", method = RequestMethod.GET)
|
||||
public ModelAndView redirection(final ModelMap model, @ModelAttribute("flashAttribute") final Object flashAttribute) {
|
||||
model.addAttribute("redirectionAttribute", flashAttribute);
|
||||
return new ModelAndView("redirection", model);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST)
|
||||
public ModelAndView redirectPostToPost(HttpServletRequest request) {
|
||||
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
|
||||
return new ModelAndView("redirect:/redirectedPostToPost");
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST)
|
||||
public ModelAndView redirectedPostToPost() {
|
||||
return new ModelAndView("redirection");
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class Company {
|
||||
|
||||
private long id;
|
||||
private String name;
|
||||
|
||||
public Company() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Company(final long id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Company [id=" + id + ", name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class HeavyResource {
|
||||
private Integer id;
|
||||
private String name;
|
||||
private String surname;
|
||||
private Integer age;
|
||||
private String address;
|
||||
|
||||
|
||||
public HeavyResource() {
|
||||
}
|
||||
|
||||
public HeavyResource(Integer id, String name, String surname, Integer age, String address) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.surname = surname;
|
||||
this.age = age;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSurname() {
|
||||
return surname;
|
||||
}
|
||||
|
||||
public void setSurname(String surname) {
|
||||
this.surname = surname;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class HeavyResourceAddressOnly {
|
||||
private Integer id;
|
||||
private String address;
|
||||
|
||||
public HeavyResourceAddressOnly() {
|
||||
}
|
||||
|
||||
public HeavyResourceAddressOnly(Integer id, String address) {
|
||||
this.id = id;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
|
||||
public class HeavyResourceAddressPartialUpdate {
|
||||
private Integer id;
|
||||
private String address;
|
||||
|
||||
public HeavyResourceAddressPartialUpdate() {
|
||||
}
|
||||
|
||||
public HeavyResourceAddressPartialUpdate(Integer id, String address) {
|
||||
this.id = id;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
public class Item {
|
||||
@JsonView(Views.Public.class)
|
||||
public int id;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
public String itemName;
|
||||
|
||||
@JsonView(Views.Internal.class)
|
||||
public String ownerName;
|
||||
|
||||
public Item() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Item(final int id, final String itemName, final String ownerName) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.ownerName = ownerName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
public String getOwnerName() {
|
||||
return ownerName;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class ItemManager {
|
||||
|
||||
public static Item getById(final int id) {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
return item;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class PactDto {
|
||||
|
||||
private boolean condition;
|
||||
private String name;
|
||||
|
||||
public PactDto() {
|
||||
}
|
||||
|
||||
public PactDto(boolean condition, String name) {
|
||||
super();
|
||||
this.condition = condition;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isCondition() {
|
||||
return condition;
|
||||
}
|
||||
|
||||
public void setCondition(boolean condition) {
|
||||
this.condition = condition;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.sampleapp.web.dto;
|
||||
|
||||
public class Views {
|
||||
public static class Public {
|
||||
}
|
||||
|
||||
public static class Internal extends Public {
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.sampleapp.web.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class ResourceNotFoundException extends RuntimeException {
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.transfer;
|
||||
|
||||
public class LoginForm {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public LoginForm() {
|
||||
}
|
||||
|
||||
public LoginForm(String username, String password) {
|
||||
super();
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.web.upload.app;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung.web.upload")
|
||||
@SpringBootApplication
|
||||
public class UploadApplication extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(final String[] args) {
|
||||
SpringApplication.run(UploadApplication.class, args);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.web.upload.client;
|
||||
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class MultipartFileUploadClient {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
uploadSingleFile();
|
||||
uploadMultipleFile();
|
||||
}
|
||||
|
||||
private static void uploadSingleFile() throws IOException {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
|
||||
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
||||
body.add("file", getTestFile());
|
||||
|
||||
|
||||
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
|
||||
String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/";
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
|
||||
System.out.println("Response code: " + response.getStatusCode());
|
||||
}
|
||||
|
||||
private static void uploadMultipleFile() throws IOException {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
|
||||
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
||||
body.add("files", getTestFile());
|
||||
body.add("files", getTestFile());
|
||||
body.add("files", getTestFile());
|
||||
|
||||
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
|
||||
String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/";
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
|
||||
System.out.println("Response code: " + response.getStatusCode());
|
||||
}
|
||||
|
||||
public static Resource getTestFile() throws IOException {
|
||||
Path testFile = Files.createTempFile("test-file", ".txt");
|
||||
System.out.println("Creating and Uploading Test File: " + testFile);
|
||||
Files.write(testFile, "Hello World !!, This is a test file.".getBytes());
|
||||
return new FileSystemResource(testFile.toFile());
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.web.upload.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/fileserver")
|
||||
public class FileServerResource {
|
||||
|
||||
@RequestMapping(path = "/singlefileupload/", method = RequestMethod.POST)
|
||||
public ResponseEntity<String> processFile(@RequestParam("file") MultipartFile file) throws IOException {
|
||||
|
||||
byte[] bytes = file.getBytes();
|
||||
|
||||
System.out.println("File Name: " + file.getOriginalFilename());
|
||||
System.out.println("File Content Type: " + file.getContentType());
|
||||
System.out.println("File Content:\n" + new String(bytes));
|
||||
|
||||
return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
|
||||
}
|
||||
|
||||
@RequestMapping(path = "/multiplefileupload/", method = RequestMethod.POST)
|
||||
public ResponseEntity<String> processFile(@RequestParam("files") List<MultipartFile> files) throws IOException {
|
||||
|
||||
for (MultipartFile file : files) {
|
||||
byte[] bytes = file.getBytes();
|
||||
|
||||
System.out.println("File Name: " + file.getOriginalFilename());
|
||||
System.out.println("File Content Type: " + file.getContentType());
|
||||
System.out.println("File Content:\n" + new String(bytes));
|
||||
}
|
||||
|
||||
return (new ResponseEntity<>("Successful", null, HttpStatus.OK));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
server.port=8082
|
||||
server.servlet.context-path=/spring-rest
|
||||
@@ -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>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.responseheaders.ResponseHeadersApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = { ResponseHeadersApplication.class,
|
||||
com.baeldung.web.upload.app.UploadApplication.class,
|
||||
})
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan("com.baeldung")
|
||||
public class SpringTestConfig {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.client;
|
||||
|
||||
public interface Consts {
|
||||
int APPLICATION_PORT = 8082;
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.baeldung.client;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import com.baeldung.resttemplate.web.dto.Foo;
|
||||
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 okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
|
||||
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<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
|
||||
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRestTemplateWrapper_whenSendGetForEntity_thenStatusOk() {
|
||||
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
|
||||
restTemplateBuilder.configure(restTemplate);
|
||||
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
|
||||
ResponseEntity<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.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<Foo> response = testRestTemplate.getForEntity(FOO_RESOURCE_URL + "/1", Foo.class);
|
||||
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRestTemplateWrapperWithCredentials_whenSendGetForEntity_thenStatusOk() {
|
||||
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
|
||||
restTemplateBuilder.configure(restTemplate);
|
||||
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder, "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);
|
||||
}
|
||||
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.pact;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
|
||||
import com.baeldung.sampleapp.config.MainApplication;
|
||||
|
||||
import au.com.dius.pact.provider.junit.PactRunner;
|
||||
import au.com.dius.pact.provider.junit.Provider;
|
||||
import au.com.dius.pact.provider.junit.State;
|
||||
import au.com.dius.pact.provider.junit.loader.PactFolder;
|
||||
import au.com.dius.pact.provider.junit.target.HttpTarget;
|
||||
import au.com.dius.pact.provider.junit.target.Target;
|
||||
import au.com.dius.pact.provider.junit.target.TestTarget;
|
||||
|
||||
@RunWith(PactRunner.class)
|
||||
@Provider("test_provider")
|
||||
@PactFolder("pacts")
|
||||
public class PactProviderLiveTest {
|
||||
|
||||
@TestTarget
|
||||
public final Target target = new HttpTarget("http", "localhost", 8082, "/spring-rest");
|
||||
|
||||
private static ConfigurableWebApplicationContext application;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() {
|
||||
application = (ConfigurableWebApplicationContext) SpringApplication.run(MainApplication.class);
|
||||
}
|
||||
|
||||
@State("test GET")
|
||||
public void toGetState() {
|
||||
}
|
||||
|
||||
@State("test POST")
|
||||
public void toPostState() {
|
||||
}
|
||||
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.baeldung.resttemplate;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class LargeFileDownloadIntegrationTest {
|
||||
|
||||
static String FILE_URL = "http://ovh.net/files/1Mio.dat";
|
||||
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
restTemplate = new RestTemplate();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResumableUrl_whenUrlCalledByHeadOption_thenExpectHeadersAvailable() {
|
||||
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
|
||||
Assertions
|
||||
.assertThat(headers.get("Accept-Ranges"))
|
||||
.contains("bytes");
|
||||
Assertions
|
||||
.assertThat(headers.getContentLength())
|
||||
.isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResumableUrl_whenDownloadCompletely_thenExpectCorrectFileSize() {
|
||||
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
|
||||
long contentLength = headers.getContentLength();
|
||||
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
|
||||
File ret = File.createTempFile("download", "tmp");
|
||||
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
|
||||
return ret;
|
||||
});
|
||||
|
||||
Assert.assertNotNull(file);
|
||||
Assertions
|
||||
.assertThat(file.length())
|
||||
.isEqualTo(contentLength);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResumableUrl_whenDownloadRange_thenExpectFileSizeEqualOrLessThanRange() {
|
||||
int range = 10;
|
||||
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
|
||||
.getHeaders()
|
||||
.set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
|
||||
File ret = File.createTempFile("download", "tmp");
|
||||
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
|
||||
return ret;
|
||||
});
|
||||
|
||||
Assert.assertNotNull(file);
|
||||
Assertions
|
||||
.assertThat(file.length())
|
||||
.isLessThanOrEqualTo(range);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResumableUrl_whenPauseDownloadAndResume_thenExpectCorrectFileSize() {
|
||||
|
||||
int range = 10;
|
||||
|
||||
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
|
||||
long contentLength = headers.getContentLength();
|
||||
|
||||
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
|
||||
.getHeaders()
|
||||
.set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
|
||||
File ret = File.createTempFile("download", "tmp");
|
||||
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
|
||||
return ret;
|
||||
});
|
||||
|
||||
Assert.assertNotNull(file);
|
||||
|
||||
Assertions
|
||||
.assertThat(file.length())
|
||||
.isLessThanOrEqualTo(range);
|
||||
|
||||
restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
|
||||
.getHeaders()
|
||||
.set("Range", String.format("bytes=%d-%d", file.length(), contentLength)), clientHttpResponse -> {
|
||||
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(file, true));
|
||||
return file;
|
||||
});
|
||||
|
||||
Assertions
|
||||
.assertThat(file.length())
|
||||
.isEqualTo(contentLength);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
package com.baeldung.resttemplate;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.encodeBase64;
|
||||
import static com.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 com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
|
||||
import com.baeldung.resttemplate.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.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
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.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
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.setErrorHandler(new RestTemplateResponseErrorHandler());
|
||||
// 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 XmlMapper();
|
||||
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, Foo.class);
|
||||
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 = getClientHttpRequestFactory();
|
||||
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.INTERNAL_SERVER_ERROR));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFooService_whenFormSubmit_thenResourceIsCreated() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
|
||||
map.add("id", "10");
|
||||
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);
|
||||
|
||||
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
|
||||
final String fooResponse = response.getBody();
|
||||
assertThat(fooResponse, notNullValue());
|
||||
assertThat(fooResponse, is("10"));
|
||||
}
|
||||
|
||||
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 getClientHttpRequestFactory() {
|
||||
final int timeout = 5;
|
||||
final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
clientHttpRequestFactory.setConnectTimeout(timeout * 1000);
|
||||
return clientHttpRequestFactory;
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.resttemplate;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.baeldung.sampleapp.config.RestClientConfig;
|
||||
import com.baeldung.transfer.LoginForm;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = RestClientConfig.class)
|
||||
public class RestTemplateLiveTest {
|
||||
|
||||
@Autowired
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() {
|
||||
LoginForm loginForm = new LoginForm("userName", "password");
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
HttpEntity<LoginForm> requestEntity = new HttpEntity<LoginForm>(loginForm, headers);
|
||||
|
||||
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class);
|
||||
|
||||
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
|
||||
assertThat(responseEntity.getHeaders()
|
||||
.get("Foo")
|
||||
.get(0), is(equalTo("bar")));
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.web.controller.redirect;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
|
||||
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration("file:src/main/webapp/WEB-INF/api-servlet.xml")
|
||||
@WebAppConfiguration
|
||||
public class RedirectControllerIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
protected WebApplicationContext wac;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRedirectOnUrlWithUsingXMLConfig_thenStatusRedirectionAndRedirectedOnUrl() throws Exception {
|
||||
mockMvc.perform(get("/redirectWithXMLConfig")).andExpect(status().is3xxRedirection()).andExpect(view().name("RedirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithXMLConfig")))
|
||||
.andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithXMLConfig"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRedirectOnUrlWithUsingRedirectPrefix_thenStatusRedirectionAndRedirectedOnUrl() throws Exception {
|
||||
mockMvc.perform(get("/redirectWithRedirectPrefix")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectPrefix")))
|
||||
.andExpect(redirectedUrl("/redirectedUrl?attribute=redirectWithRedirectPrefix"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRedirectOnUrlWithUsingRedirectAttributes_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception {
|
||||
mockMvc.perform(get("/redirectWithRedirectAttributes")).andExpect(status().is3xxRedirection()).andExpect(flash().attribute("flashAttribute", equalTo("redirectWithRedirectAttributes")))
|
||||
.andExpect(model().attribute("attribute", equalTo("redirectWithRedirectAttributes"))).andExpect(model().attribute("flashAttribute", equalTo(null))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectAttributes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRedirectOnUrlWithUsingRedirectView_thenStatusRedirectionAndRedirectedOnUrlAndAddedAttributeToFlashScope() throws Exception {
|
||||
mockMvc.perform(get("/redirectWithRedirectView")).andExpect(status().is3xxRedirection()).andExpect(model().attribute("attribute", equalTo("redirectWithRedirectView"))).andExpect(redirectedUrl("redirectedUrl?attribute=redirectWithRedirectView"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRedirectOnUrlWithUsingForwardPrefix_thenStatusOkAndForwardedOnUrl() throws Exception {
|
||||
mockMvc.perform(get("/forwardWithForwardPrefix")).andExpect(status().isOk()).andExpect(view().name("forward:/redirectedUrl")).andExpect(model().attribute("attribute", equalTo("redirectWithForwardPrefix"))).andExpect(forwardedUrl("/redirectedUrl"));
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.web.handler;
|
||||
|
||||
import com.baeldung.resttemplate.web.exception.NotFoundException;
|
||||
import com.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
|
||||
import com.baeldung.resttemplate.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();
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.web.service;
|
||||
|
||||
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;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import com.baeldung.SpringTestConfig;
|
||||
import com.baeldung.resttemplate.web.model.Employee;
|
||||
import com.baeldung.resttemplate.web.service.EmployeeService;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
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 com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = SpringTestConfig.class)
|
||||
public class EmployeeServiceMockRestServiceServerUnitTest {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceMockRestServiceServerUnitTest.class);
|
||||
|
||||
@Autowired
|
||||
private EmployeeService empService;
|
||||
|
||||
@Autowired
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
private MockRestServiceServer mockServer;
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
mockServer = MockRestServiceServer.createServer(restTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMockingIsDoneByMockRestServiceServer_whenGetIsCalled_shouldReturnMockedObject() throws Exception {
|
||||
Employee emp = new Employee("E001", "Eric Simmons");
|
||||
|
||||
mockServer.expect(ExpectedCount.once(),
|
||||
requestTo(new URI("http://localhost:8080/employee/E001")))
|
||||
.andExpect(method(HttpMethod.GET))
|
||||
.andRespond(withStatus(HttpStatus.OK)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body(mapper.writeValueAsString(emp)));
|
||||
|
||||
Employee employee = empService.getEmployee("E001");
|
||||
mockServer.verify();
|
||||
Assert.assertEquals(emp, employee);
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.web.service;
|
||||
|
||||
import com.baeldung.resttemplate.web.model.Employee;
|
||||
import com.baeldung.resttemplate.web.service.EmployeeService;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class EmployeeServiceUnitTest {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceUnitTest.class);
|
||||
|
||||
@Mock
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@InjectMocks
|
||||
private EmployeeService empService = new EmployeeService();
|
||||
|
||||
@Test
|
||||
public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() throws Exception {
|
||||
Employee emp = new Employee("E001", "Eric Simmons");
|
||||
Mockito.when(restTemplate.getForEntity("http://localhost:8080/employee/E001", Employee.class))
|
||||
.thenReturn(new ResponseEntity(emp, HttpStatus.OK));
|
||||
|
||||
Employee employee = empService.getEmployee("E001");
|
||||
|
||||
Assert.assertEquals(emp, employee);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -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>
|
||||
Reference in New Issue
Block a user