[BAEL-14088] - Moved code for RequestBody and ResponseBody annotations article

This commit is contained in:
amit2103
2019-04-13 23:16:33 +05:30
parent 9df90567d4
commit 6b0a96291e
9 changed files with 26 additions and 23 deletions

View File

@@ -0,0 +1,29 @@
package com.baeldung.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.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;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.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;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.services;
import com.baeldung.transfer.LoginForm;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
public boolean fakeAuthenticate(LoginForm lf) {
return true;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.transfer;
public class ResponseTransfer {
private String text;
public ResponseTransfer(String text) {
this.setText(text);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.web.controller;
import com.baeldung.services.ExampleService;
import com.baeldung.transfer.ResponseTransfer;
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.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.baeldung.transfer.LoginForm;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/post")
public class ExamplePostController {
private static Logger log = LoggerFactory.getLogger(ExamplePostController.class);
@Autowired ExampleService exampleService;
@PostMapping("/request")
public ResponseEntity postController(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
exampleService.fakeAuthenticate(loginForm);
return ResponseEntity.ok(HttpStatus.OK);
}
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(@RequestBody LoginForm loginForm) {
log.debug("POST received - serializing LoginForm: " + loginForm.getPassword() + " " + loginForm.getUsername());
return new ResponseTransfer("Thanks For Posting!!!");
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.controllers;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.baeldung.SpringBootRestApplication;
import com.baeldung.services.ExampleService;
import com.baeldung.transfer.LoginForm;
import com.baeldung.web.controller.ExamplePostController;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootRestApplication.class)
public class ExamplePostControllerRequestIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;
@InjectMocks private ExamplePostController exampleController;
private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}";
private LoginForm lf = new LoginForm();
@Before
public void preTest() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(exampleController)
.build();
lf.setPassword("password");
lf.setUsername("username");
}
@Test
public void requestBodyTest() {
try {
when(exampleService.fakeAuthenticate(lf)).thenReturn(true);
mockMvc
.perform(post("/post/request")
.content(jsonBody)
.contentType("application/json"))
.andDo(print())
.andExpect(status().isOk());
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}

View File

@@ -0,0 +1,60 @@
package com.baeldung.controllers;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.baeldung.SpringBootRestApplication;
import com.baeldung.services.ExampleService;
import com.baeldung.transfer.LoginForm;
import com.baeldung.web.controller.ExamplePostController;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootRestApplication.class)
public class ExamplePostControllerResponseIntegrationTest {
MockMvc mockMvc;
@Mock private ExampleService exampleService;
@InjectMocks private ExamplePostController exampleController;
private final String jsonBody = "{\"username\": \"username\", \"password\": \"password\"}";
private LoginForm lf = new LoginForm();
@Before
public void preTest() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(exampleController)
.build();
lf.setPassword("password");
lf.setUsername("username");
}
@Test
public void requestBodyTest() {
try {
when(exampleService.fakeAuthenticate(lf)).thenReturn(true);
mockMvc
.perform(post("/post/response")
.content(jsonBody)
.contentType("application/json"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"text\":\"Thanks For Posting!!!\"}"));
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}

View File

@@ -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.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")));
}
}