JAVA-3540: Move spring-resttemplate into spring-web-modules

This commit is contained in:
Krzysztof Woyke
2021-01-05 14:10:30 +01:00
parent a97e1c360e
commit f361ccc834
72 changed files with 2 additions and 3 deletions
+1
View File
@@ -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.
File diff suppressed because it is too large Load Diff
@@ -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);
}
}
@@ -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";
}
}
@@ -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);
}
}
@@ -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...");
}
}
@@ -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);
}
}
@@ -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());
}
}
@@ -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());
}
}
@@ -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;
}
}
@@ -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";
}
}
@@ -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());
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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());
}
}
@@ -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 + "]";
}
}
@@ -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;
}
}
@@ -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));
}
}
@@ -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;
}
}
@@ -0,0 +1,4 @@
package com.baeldung.resttemplate.web.exception;
public class NotFoundException extends RuntimeException {
}
@@ -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();
}
}
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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());
}
*/
}

Some files were not shown because too many files have changed in this diff Show More