JAVA-3539 Move spring-resttemplate-2 module

This commit is contained in:
mikr
2020-12-29 18:52:31 +01:00
parent 391efe067c
commit 469e5c5c86
38 changed files with 2 additions and 3 deletions
@@ -0,0 +1,38 @@
package com.baeldung.compress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
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;
public class CompressingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(CompressingClientHttpRequestInterceptor.class);
private static final String GZIP_ENCODING = "gzip";
/**
* Compress a request body using Gzip and add Http headers.
*
* @param req
* @param body
* @param exec
* @return
* @throws IOException
*/
@Override
public ClientHttpResponse intercept(HttpRequest req, byte[] body, ClientHttpRequestExecution exec)
throws IOException {
LOG.info("Compressing request...");
HttpHeaders httpHeaders = req.getHeaders();
httpHeaders.add(HttpHeaders.CONTENT_ENCODING, GZIP_ENCODING);
httpHeaders.add(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING);
return exec.execute(req, GzipUtils.compress(body));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.compress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
public class GzipUtils {
/**
* Gzip a string.
*
* @param text
* @return
* @throws Exception
*/
public static byte[] compress(String text) throws Exception {
return GzipUtils.compress(text.getBytes(StandardCharsets.UTF_8));
}
/**
* Gzip a byte array.
*
* @param body
* @return
* @throws IOException
*/
public static byte[] compress(byte[] body) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {
gzipOutputStream.write(body);
}
return baos.toByteArray();
}
/**
* Decompress a Gzipped byte array to a String.
*
* @param body
* @return
* @throws IOException
*/
public static String decompress(byte[] body) throws IOException {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(body))) {
return IOUtils.toString(gzipInputStream, StandardCharsets.UTF_8);
}
}
}
@@ -0,0 +1,38 @@
package com.baeldung.compress;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configure Jetty web server so it handles compressed requests.
*/
@Configuration
public class JettyWebServerConfiguration {
private static final int MIN_BYTES = 1;
/**
* Customise the Jetty web server to automatically decompress requests.
*/
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
factory.addServerCustomizers(server -> {
GzipHandler gzipHandler = new GzipHandler();
// Enable request decompression
gzipHandler.setInflateBufferSize(MIN_BYTES);
gzipHandler.setHandler(server.getHandler());
HandlerCollection handlerCollection = new HandlerCollection(gzipHandler);
server.setHandler(handlerCollection);
});
return factory;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.compress;
public class Message {
private String text;
public Message() {
}
public Message(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Message {");
sb.append("text='").append(text).append('\'');
sb.append('}');
return sb.toString();
}
}
@@ -0,0 +1,38 @@
package com.baeldung.compress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class MessageController {
protected static final String PROCESSED = "Processed ";
protected static final String REQUEST_MAPPING = "process";
private static final Logger LOG = LoggerFactory.getLogger(MessageController.class);
/**
* A simple endpoint that responds with "Processed " + supplied Message content.
*
* @param headers
* @param message
* @return
*/
@PostMapping(value = REQUEST_MAPPING)
public ResponseEntity<String> processMessage(@RequestHeader Map<String, String> headers,
@RequestBody Message message) {
// Print headers
headers.forEach((k, v) -> LOG.info(k + "=" + v));
return ResponseEntity.ok(PROCESSED + message.getText());
}
}
@@ -0,0 +1,21 @@
package com.baeldung.compress;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfiguration {
/**
* A RestTemplate that compresses requests.
*
* @return RestTemplate
*/
@Bean
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(new CompressingClientHttpRequestInterceptor());
return restTemplate;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.compress;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
public class SpringCompressRequestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCompressRequestApplication.class, args);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.resttemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestTemplateConfigurationApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.resttemplate.json.consumer.service;
import java.util.List;
public interface UserConsumerService {
List<String> processUserDataFromObjectArray();
List<String> processUserDataFromUserArray();
List<String> processUserDataFromUserList();
List<String> processNestedUserDataFromUserArray();
List<String> processNestedUserDataFromUserList();
}
@@ -0,0 +1,90 @@
package com.baeldung.resttemplate.json.consumer.service;
import com.baeldung.resttemplate.json.model.Address;
import com.baeldung.resttemplate.json.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class UserConsumerServiceImpl implements UserConsumerService {
private static final String BASE_URL = "http://localhost:8080/users";
private final RestTemplate restTemplate;
private static final ObjectMapper mapper = new ObjectMapper();
public UserConsumerServiceImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public List<String> processUserDataFromObjectArray() {
ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(BASE_URL, Object[].class);
Object[] objects = responseEntity.getBody();
return Arrays.stream(objects)
.map(object -> mapper.convertValue(object, User.class))
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processUserDataFromUserArray() {
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class);
User[] userArray = responseEntity.getBody();
return Arrays.stream(userArray)
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processUserDataFromUserList() {
ResponseEntity<List<User>> responseEntity =
restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {}
);
List<User> users = responseEntity.getBody();
return users.stream()
.map(User::getName)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedUserDataFromUserArray() {
ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class);
User[] userArray = responseEntity.getBody();
//we can get more info if we need :
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();
return Arrays.stream(userArray)
.flatMap(user -> user.getAddressList().stream())
.map(Address::getPostCode)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedUserDataFromUserList() {
ResponseEntity<List<User>> responseEntity =
restTemplate.exchange(
BASE_URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {}
);
List<User> userList = responseEntity.getBody();
return userList.stream()
.flatMap(user -> user.getAddressList().stream())
.map(Address::getPostCode)
.collect(Collectors.toList());
}
}
@@ -0,0 +1,29 @@
package com.baeldung.resttemplate.json.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Address {
private final String addressLine1;
private final String addressLine2;
private final String town;
private final String postCode;
@JsonCreator
public Address(
@JsonProperty("addressLine1") String addressLine1,
@JsonProperty("addressLine2") String addressLine2,
@JsonProperty("town") String town,
@JsonProperty("postCode") String postCode) {
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.town = town;
this.postCode = postCode;
}
public String getPostCode() {
return postCode;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.resttemplate.json.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private final int id;
private final String name;
private final List<Address> addressList;
@JsonCreator
public User(
@JsonProperty("id") int id,
@JsonProperty("name") String name,
@JsonProperty("addressList") List<Address> addressList) {
this.id = id;
this.name = name;
this.addressList = addressList;
}
public String getName() {
return name;
}
public List<Address> getAddressList() { return addressList; }
}
@@ -0,0 +1,17 @@
package com.baeldung.resttemplate.logging.web.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@PostMapping("/persons")
public List<String> getPersons() {
return Arrays.asList(new String[] { "Lucie", "Jackie", "Danesh", "Tao" });
}
}
@@ -0,0 +1,38 @@
package com.baeldung.resttemplate.web.controller;
import javax.servlet.http.HttpServletResponse;
import com.baeldung.resttemplate.web.service.PersonService;
import com.baeldung.resttemplate.web.dto.Person;
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,32 @@
package com.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,10 @@
package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.dto.Person;
public interface PersonService {
public Person saveUpdatePerson(Person person);
public Person findPersonById(Integer id);
}
@@ -0,0 +1,19 @@
package com.baeldung.resttemplate.web.service;
import com.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,17 @@
package com.baeldung.sampleapp.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan({ "com.baeldung.sampleapp.web" })
public class WebConfig implements WebMvcConfigurer {
public WebConfig() {
super();
}
}
@@ -0,0 +1,25 @@
package com.baeldung.sampleapp.web.controller.mediatypes;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import com.baeldung.sampleapp.web.dto.BaeldungItem;
import com.baeldung.sampleapp.web.dto.BaeldungItemV2;
@RestController
@RequestMapping(value = "/", produces = "application/vnd.baeldung.api.v1+json")
public class CustomMediaTypeController {
@RequestMapping(method = RequestMethod.GET, value = "/public/api/items/{id}", produces = "application/vnd.baeldung.api.v1+json")
public @ResponseBody BaeldungItem getItem(@PathVariable("id") String id) {
return new BaeldungItem("itemId1");
}
@RequestMapping(method = RequestMethod.GET, value = "/public/api/items/{id}", produces = "application/vnd.baeldung.api.v2+json")
public @ResponseBody BaeldungItemV2 getItemSecondAPIVersion(@PathVariable("id") String id) {
return new BaeldungItemV2("itemName");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.sampleapp.web.dto;
public class BaeldungItem {
private final String itemId;
public BaeldungItem(String itemId) {
this.itemId = itemId;
}
public String getItemId() {
return itemId;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.sampleapp.web.dto;
public class BaeldungItemV2 {
private final String itemName;
public BaeldungItemV2(String itemName) {
this.itemName = itemName;
}
public String getItemName() {
return itemName;
}
}