JAVA-2113: Split or move spring-resttemplate module (#9753)
* JAVA-2113: Move Proxies With RestTemplate to spring-resttemplate-2 * JAVA-2113: Move A Custom Media Type for a Spring REST API to spring-resttemplate-2 * JAVA-2113: Move RestTemplate Post Request with JSON to spring-resttemplate-2 * JAVA-2113: Move Download an Image or a File with Spring MVC to spring-boot-mvc-3 * JAVA-2113: Fix the test
This commit is contained in:
@@ -5,3 +5,6 @@ This module contains articles about Spring RestTemplate
|
||||
### Relevant Articles:
|
||||
|
||||
- [Spring RestTemplate Request/Response Logging](https://www.baeldung.com/spring-resttemplate-logging)
|
||||
- [Proxies With RestTemplate](https://www.baeldung.com/java-resttemplate-proxy)
|
||||
- [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type)
|
||||
- [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.resttemplate;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class RestTemplateConfigurationApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.resttemplate.postjson;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
||||
import com.baeldung.resttemplate.RestTemplateConfigurationApplication;
|
||||
import com.baeldung.resttemplate.web.dto.Person;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = RestTemplateConfigurationApplication.class)
|
||||
public class PersonAPILiveTest {
|
||||
|
||||
private static String createPersonUrl;
|
||||
private static String updatePersonUrl;
|
||||
|
||||
private static RestTemplate restTemplate;
|
||||
|
||||
private static HttpHeaders headers;
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private static JSONObject personJsonObject;
|
||||
|
||||
@BeforeClass
|
||||
public static void runBeforeAllTestMethods() throws JSONException {
|
||||
createPersonUrl = "http://localhost:8082/spring-rest/createPerson";
|
||||
updatePersonUrl = "http://localhost:8082/spring-rest/updatePerson";
|
||||
|
||||
restTemplate = new RestTemplate();
|
||||
|
||||
headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
personJsonObject = new JSONObject();
|
||||
personJsonObject.put("id", 1);
|
||||
personJsonObject.put("name", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataIsJson_whenDataIsPostedByPostForObject_thenResponseBodyIsNotNull() throws IOException {
|
||||
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
|
||||
String personResultAsJsonStr = restTemplate.postForObject(createPersonUrl, request, String.class);
|
||||
JsonNode root = objectMapper.readTree(personResultAsJsonStr);
|
||||
|
||||
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
|
||||
|
||||
assertNotNull(personResultAsJsonStr);
|
||||
assertNotNull(root);
|
||||
assertNotNull(root.path("name")
|
||||
.asText());
|
||||
|
||||
assertNotNull(person);
|
||||
assertNotNull(person.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataIsJson_whenDataIsPostedByPostForEntity_thenResponseBodyIsNotNull() throws IOException {
|
||||
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
|
||||
ResponseEntity<String> responseEntityStr = restTemplate.postForEntity(createPersonUrl, request, String.class);
|
||||
JsonNode root = objectMapper.readTree(responseEntityStr.getBody());
|
||||
|
||||
ResponseEntity<Person> responseEntityPerson = restTemplate.postForEntity(createPersonUrl, request, Person.class);
|
||||
|
||||
assertNotNull(responseEntityStr.getBody());
|
||||
assertNotNull(root.path("name")
|
||||
.asText());
|
||||
|
||||
assertNotNull(responseEntityPerson.getBody());
|
||||
assertNotNull(responseEntityPerson.getBody()
|
||||
.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataIsJson_whenDataIsPostedByPostForLocation_thenResponseBodyIsTheLocationHeader() throws JsonProcessingException {
|
||||
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
|
||||
URI locationHeader = restTemplate.postForLocation(updatePersonUrl, request);
|
||||
|
||||
assertNotNull(locationHeader);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.resttemplate.proxy;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.Proxy.Type;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* This class is used to test a request using {@link RestTemplate} with {@link Proxy}
|
||||
* using a {@link SimpleClientHttpRequestFactory} as configuration.
|
||||
* <br />
|
||||
* <br />
|
||||
*
|
||||
* Before running the test we should change the <code>PROXY_SERVER_HOST</code>
|
||||
* and <code>PROXY_SERVER_PORT</code> constants in our class to match our preferred proxy configuration.
|
||||
*/
|
||||
public class RequestFactoryLiveTest {
|
||||
|
||||
private static final String PROXY_SERVER_HOST = "127.0.0.1";
|
||||
private static final int PROXY_SERVER_PORT = 8080;
|
||||
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
|
||||
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setProxy(proxy);
|
||||
|
||||
restTemplate = new RestTemplate(requestFactory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenRequestedWithProxy_thenResponseBodyIsOk() {
|
||||
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
|
||||
|
||||
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.resttemplate.proxy;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.net.Proxy;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.boot.web.client.RestTemplateCustomizer;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* This class is used to test a request using {@link RestTemplate} with {@link Proxy}
|
||||
* using a {@link RestTemplateCustomizer} as configuration.
|
||||
* <br />
|
||||
* <br />
|
||||
*
|
||||
* Before running the test we should change the <code>PROXY_SERVER_HOST</code>
|
||||
* and <code>PROXY_SERVER_PORT</code> constants in our class to match our preferred proxy configuration.
|
||||
*/
|
||||
public class RestTemplateCustomizerLiveTest {
|
||||
|
||||
private static final String PROXY_SERVER_HOST = "127.0.0.1";
|
||||
private static final int PROXY_SERVER_PORT = 8080;
|
||||
|
||||
RestTemplate restTemplate;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
restTemplate = new RestTemplateBuilder(new ProxyCustomizer()).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRestTemplate_whenRequestedWithProxy_thenResponseBodyIsOk() {
|
||||
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
|
||||
|
||||
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
|
||||
}
|
||||
|
||||
private static class ProxyCustomizer implements RestTemplateCustomizer {
|
||||
|
||||
@Override
|
||||
public void customize(RestTemplate restTemplate) {
|
||||
HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
|
||||
HttpClient httpClient = HttpClientBuilder.create()
|
||||
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
|
||||
@Override
|
||||
public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
|
||||
return super.determineProxy(target, request, context);
|
||||
}
|
||||
})
|
||||
.build();
|
||||
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.web.controller.mediatypes;
|
||||
|
||||
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.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import com.baeldung.sampleapp.config.WebConfig;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = WebConfig.class)
|
||||
@WebAppConfiguration
|
||||
public class CustomMediaTypeControllerIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceUrl_whenGetWithProperAcceptHeaderFirstAPIVersion_thenReturn200() throws Exception {
|
||||
mockMvc.perform(get("/public/api/items/1").accept("application/vnd.baeldung.api.v1+json")).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceUrl_whenGetWithProperAcceptHeaderSecondVersion_thenReturn200() throws Exception {
|
||||
mockMvc.perform(get("/public/api/items/2").accept("application/vnd.baeldung.api.v2+json")).andExpect(status().isOk());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.web.controller.mediatypes;
|
||||
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class)
|
||||
public class CustomMediaTypeControllerLiveTest {
|
||||
private static final String URL_PREFIX = "http://localhost:8082/spring-rest";
|
||||
|
||||
@Test
|
||||
public void givenServiceEndpoint_whenGetRequestFirstAPIVersion_thenShouldReturn200() {
|
||||
given()
|
||||
.accept("application/vnd.baeldung.api.v1+json")
|
||||
.when()
|
||||
.get(URL_PREFIX + "/public/api/items/1")
|
||||
.then()
|
||||
.contentType(ContentType.JSON).and().statusCode(200);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenServiceEndpoint_whenGetRequestSecondAPIVersion_thenShouldReturn200() {
|
||||
given()
|
||||
.accept("application/vnd.baeldung.api.v2+json")
|
||||
.when()
|
||||
.get(URL_PREFIX + "/public/api/items/2")
|
||||
.then()
|
||||
.contentType(ContentType.JSON).and().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.web.controller.mediatypes;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
|
||||
@Configuration
|
||||
@ComponentScan({ "com.baeldung.web" })
|
||||
public class TestConfig {
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user