Bael-624 - Code Review fixes

This commit is contained in:
Kyle Doyle
2019-10-07 22:23:44 -04:00
parent db85c8f275
commit 07859c6e38
20348 changed files with 1637653 additions and 0 deletions
@@ -0,0 +1,14 @@
package org.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 org.baeldung.resttemplate.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
/**
* interceptor to log incoming requests
*/
public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
logRequestDetails(request);
return execution.execute(request, body);
}
private void logRequestDetails(HttpRequest request) {
LOGGER.info("Request Headers: {}", request.getHeaders());
LOGGER.info("Request Method: {}", request.getMethod());
LOGGER.info("Request URI: {}", request.getURI());
}
}
@@ -0,0 +1,14 @@
package org.baeldung.resttemplate.configuration;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.web.client.RestTemplate;
/**
* customize rest template with an interceptor
*/
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor());
}
}
@@ -0,0 +1,124 @@
package org.baeldung.resttemplate.configuration;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import org.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 org.baeldung.resttemplate.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Controller to test RestTemplate configuration
*/
@RestController
public class HelloController {
private static final String RESOURCE_URL = "http://localhost:8082/spring-rest/baz";
private RestTemplate restTemplate;
@Autowired
public HelloController(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
@RequestMapping("/foo")
public String foo() {
ResponseEntity<String> response = restTemplate.getForEntity(RESOURCE_URL, String.class);
return response.getBody();
}
@RequestMapping("/baz")
public String baz() {
return "Foo";
}
}
@@ -0,0 +1,33 @@
package org.baeldung.resttemplate.configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableAutoConfiguration
@ComponentScan("org.baeldung.resttemplate.configuration")
public class SpringConfig {
@Bean
@Qualifier("customRestTemplateCustomizer")
public CustomRestTemplateCustomizer customRestTemplateCustomizer() {
return new CustomRestTemplateCustomizer();
}
@Bean
@DependsOn(value = {"customRestTemplateCustomizer"})
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder(customRestTemplateCustomizer());
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@@ -0,0 +1,38 @@
package org.baeldung.resttemplate.web.controller;
import javax.servlet.http.HttpServletResponse;
import org.baeldung.resttemplate.web.dto.Person;
import org.baeldung.resttemplate.web.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
public class PersonAPI {
@Autowired
private PersonService personService;
@GetMapping("/")
public String home() {
return "Spring boot is working!";
}
@PostMapping(value = "/createPerson", consumes = "application/json", produces = "application/json")
public Person createPerson(@RequestBody Person person) {
return personService.saveUpdatePerson(person);
}
@PostMapping(value = "/updatePerson", consumes = "application/json", produces = "application/json")
public Person updatePerson(@RequestBody Person person, HttpServletResponse response) {
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/findPerson/" + person.getId())
.toUriString());
return personService.saveUpdatePerson(person);
}
}
@@ -0,0 +1,45 @@
package org.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,32 @@
package org.baeldung.resttemplate.web.dto;
public class Person {
private Integer id;
private String name;
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
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;
}
}
@@ -0,0 +1,4 @@
package org.baeldung.resttemplate.web.exception;
public class NotFoundException extends RuntimeException {
}
@@ -0,0 +1,45 @@
package org.baeldung.resttemplate.web.handler;
import java.io.IOException;
import org.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 org.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,48 @@
package org.baeldung.resttemplate.web.model;
import java.util.Date;
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 org.baeldung.resttemplate.web.service;
import org.baeldung.resttemplate.web.handler.RestTemplateResponseErrorHandler;
import org.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 org.baeldung.resttemplate.web.service;
import org.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,10 @@
package org.baeldung.resttemplate.web.service;
import org.baeldung.resttemplate.web.dto.Person;
public interface PersonService {
public Person saveUpdatePerson(Person person);
public Person findPersonById(Integer id);
}
@@ -0,0 +1,19 @@
package org.baeldung.resttemplate.web.service;
import org.baeldung.resttemplate.web.dto.Person;
import org.springframework.stereotype.Component;
@Component
public class PersonServiceImpl implements PersonService {
@Override
public Person saveUpdatePerson(Person person) {
return person;
}
@Override
public Person findPersonById(Integer id) {
return new Person(id, "John");
}
}
@@ -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>