[BAEL-18367] Moving articles from rest-spring-** pt 4
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
|
||||
import org.springframework.oxm.xstream.XStreamMarshaller;
|
||||
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
|
||||
/*
|
||||
* Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan({ "com.baeldung.web", "com.baeldung.requestmapping" })
|
||||
public class MvcConfig implements WebMvcConfigurer {
|
||||
|
||||
public MvcConfig() {
|
||||
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"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
|
||||
configurer.defaultContentType(MediaType.APPLICATION_JSON);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.controllers;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.request.async.DeferredResult;
|
||||
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
@RestController
|
||||
public class DeferredResultController {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
|
||||
|
||||
@GetMapping("/async-deferredresult")
|
||||
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
|
||||
LOG.info("Received async-deferredresult request");
|
||||
DeferredResult<ResponseEntity<?>> output = new DeferredResult<>();
|
||||
ForkJoinPool.commonPool().submit(() -> {
|
||||
LOG.info("Processing in separate thread");
|
||||
try {
|
||||
Thread.sleep(6000);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
output.setResult(ResponseEntity.ok("ok"));
|
||||
});
|
||||
LOG.info("servlet thread freed");
|
||||
return output;
|
||||
}
|
||||
|
||||
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
|
||||
LOG.info("Received async request with a configured timeout");
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
|
||||
deferredResult.onTimeout(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
deferredResult.setErrorResult(
|
||||
ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timeout occurred."));
|
||||
}
|
||||
});
|
||||
ForkJoinPool.commonPool().submit(() -> {
|
||||
LOG.info("Processing in separate thread");
|
||||
try {
|
||||
Thread.sleep(600l);
|
||||
deferredResult.setResult(ResponseEntity.ok("ok"));
|
||||
} catch (InterruptedException e) {
|
||||
LOG.info("Request processing interrupted");
|
||||
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("INTERNAL_SERVER_ERROR occurred."));
|
||||
}
|
||||
|
||||
});
|
||||
LOG.info("servlet thread freed");
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
|
||||
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
|
||||
ForkJoinPool.commonPool().submit(() -> {
|
||||
try {
|
||||
// Exception occurred in processing
|
||||
throw new Exception();
|
||||
} catch (Exception e) {
|
||||
LOG.info("Request processing failed");
|
||||
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("INTERNAL_SERVER_ERROR occurred."));
|
||||
}
|
||||
});
|
||||
return deferredResult;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.requestmapping;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/ex")
|
||||
public class BarMappingExamplesController {
|
||||
|
||||
public BarMappingExamplesController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// with @RequestParam
|
||||
|
||||
@RequestMapping(value = "/bars")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = "id")
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/bars", params = { "id", "second" })
|
||||
@ResponseBody
|
||||
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") final long id) {
|
||||
return "Get a specific Bar with id=" + id;
|
||||
}
|
||||
|
||||
// with @PathVariable
|
||||
|
||||
@RequestMapping(value = "/bars/{numericId:[\\d]+}")
|
||||
@ResponseBody
|
||||
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
|
||||
return "Get a specific Bar with id=" + numericId;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.requestmapping;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.web.dto.Bazz;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/bazz")
|
||||
public class BazzNewMappingsExampleController {
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<?> getBazzs() throws JsonProcessingException{
|
||||
List<Bazz> data = Arrays.asList(
|
||||
new Bazz("1", "Bazz1"),
|
||||
new Bazz("2", "Bazz2"),
|
||||
new Bazz("3", "Bazz3"),
|
||||
new Bazz("4", "Bazz4"));
|
||||
return new ResponseEntity<>(data, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<?> getBazz(@PathVariable String id){
|
||||
return new ResponseEntity<>(new Bazz(id, "Bazz"+id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<?> newBazz(@RequestParam("name") String name){
|
||||
return new ResponseEntity<>(new Bazz("5", name), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<?> updateBazz(@PathVariable String id,
|
||||
@RequestParam("name") String name){
|
||||
return new ResponseEntity<>(new Bazz(id, name), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<?> deleteBazz(@PathVariable String id){
|
||||
return new ResponseEntity<>(new Bazz(id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.baeldung.requestmapping;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(value = "/ex")
|
||||
public class FooMappingExamplesController {
|
||||
|
||||
public FooMappingExamplesController() {
|
||||
super();
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
// mapping examples
|
||||
|
||||
@RequestMapping(value = "/foos")
|
||||
@ResponseBody
|
||||
public String getFoosBySimplePath() {
|
||||
return "Simple Get some Foos";
|
||||
}
|
||||
|
||||
// with @PathVariable
|
||||
|
||||
@RequestMapping(value = "/foos/{id}")
|
||||
@ResponseBody
|
||||
public String getFoosBySimplePathWithPathVariable(@PathVariable final long id) {
|
||||
return "Get a specific Foo with id=" + id;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos/{fooid}/bar/{barid}")
|
||||
@ResponseBody
|
||||
public String getFoosBySimplePathWithPathVariables(@PathVariable final long fooid, @PathVariable final long barid) {
|
||||
return "Get a specific Bar with id=" + barid + " from a Foo with id=" + fooid;
|
||||
}
|
||||
|
||||
// other HTTP verbs
|
||||
|
||||
@RequestMapping(value = "/foos", method = RequestMethod.POST)
|
||||
@ResponseBody
|
||||
public String postFoos() {
|
||||
return "Post some Foos";
|
||||
}
|
||||
|
||||
// with headers
|
||||
|
||||
@RequestMapping(value = "/foos", headers = "key=val")
|
||||
@ResponseBody
|
||||
public String getFoosWithHeader() {
|
||||
return "Get some Foos with Header";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
|
||||
@ResponseBody
|
||||
public String getFoosWithHeaders() {
|
||||
return "Get some Foos with Header";
|
||||
}
|
||||
|
||||
// @RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")
|
||||
// @ResponseBody
|
||||
// public String getFoosAsJsonFromBrowser() {
|
||||
// return "Get some Foos with Header Old";
|
||||
// }
|
||||
|
||||
@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })
|
||||
@ResponseBody
|
||||
public String getFoosAsJsonFromREST() {
|
||||
return "Get some Foos with Header New";
|
||||
}
|
||||
|
||||
// advanced - multiple mappings
|
||||
|
||||
@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
|
||||
@ResponseBody
|
||||
public String getFoosOrBarsByPath() {
|
||||
return "Advanced - Get some Foos or Bars";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "*")
|
||||
@ResponseBody
|
||||
public String getFallback() {
|
||||
return "Fallback for GET Requests";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public String allFallback() {
|
||||
return "Fallback for All Requests";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public String putAndPostFoos() {
|
||||
return "Advanced - PUT and POST within single method";
|
||||
}
|
||||
|
||||
// --- Ambiguous Mapping
|
||||
|
||||
@GetMapping(value = "foos/duplicate" )
|
||||
public String duplicate() {
|
||||
return "Duplicate";
|
||||
}
|
||||
|
||||
// uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping
|
||||
|
||||
// @GetMapping(value = "foos/duplicate" )
|
||||
// public String duplicateEx() {
|
||||
// return "Duplicate";
|
||||
// }
|
||||
|
||||
@GetMapping(value = "foos/duplicate/xml", produces = MediaType.APPLICATION_XML_VALUE)
|
||||
public String duplicateXml() {
|
||||
return "Duplicate Xml";
|
||||
}
|
||||
|
||||
@GetMapping(value = "foos/duplicate/json", produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public String duplicateJson() {
|
||||
return "Duplicate Json";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.web.controller.status;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@Controller
|
||||
public class ExampleController {
|
||||
|
||||
@RequestMapping(value = "/controller", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public ResponseEntity sendViaResponseEntity() {
|
||||
return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/exception", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public ResponseEntity sendViaException() {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.web.controller.status;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "To show an example of a custom message")
|
||||
public class ForbiddenException extends RuntimeException {
|
||||
private static final long serialVersionUID = 6826605655586311552L;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.web.dto;
|
||||
|
||||
public class Bazz {
|
||||
|
||||
|
||||
public String id;
|
||||
public String name;
|
||||
|
||||
public Bazz(String id){
|
||||
this.id = id;
|
||||
}
|
||||
public Bazz(String id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Bazz [id=" + id + ", name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
||||
45
spring-rest-http/src/main/java/com/baeldung/web/dto/Foo.java
Normal file
45
spring-rest-http/src/main/java/com/baeldung/web/dto/Foo.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.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,82 @@
|
||||
|
||||
package com.baeldung.requestmapping;
|
||||
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
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.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
|
||||
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.config.MvcConfig;
|
||||
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MvcConfig.class)
|
||||
@WebAppConfiguration
|
||||
@AutoConfigureWebClient
|
||||
public class BazzNewMappingsExampleIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingAllBazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(get("/bazz"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(4)))
|
||||
.andExpect(jsonPath("$[1].id", is("2")))
|
||||
.andExpect(jsonPath("$[1].name", is("Bazz2")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGettingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(get("/bazz/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("1")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(post("/bazz").param("name", "Bazz5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz5")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdatingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(put("/bazz/5").param("name", "Bazz6"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")))
|
||||
.andExpect(jsonPath("$.name", is("Bazz6")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeletingABazz_thenSuccess() throws Exception{
|
||||
mockMvc.perform(delete("/bazz/5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", is("5")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.baeldung.responseheaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
public class ResponseHeaderLiveTest {
|
||||
|
||||
private static final String BASE_URL = "http://localhost:8082/spring-rest";
|
||||
private static final String SINGLE_BASE_URL = BASE_URL + "/single-response-header";
|
||||
private static final String FILTER_BASE_URL = BASE_URL + "/filter-response-header";
|
||||
private static final String SERVICE_SINGLE_RESPONSE_HEADER = "Baeldung-Example-Header";
|
||||
private static final String SERVICE_FILTER_RESPONSE_HEADER = "Baeldung-Example-Filter-Header";
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate template;
|
||||
|
||||
@Test
|
||||
public void whenHttpServletResponseRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/http-servlet-response";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-HttpServletResponse"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityConstructorRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/response-entity-constructor";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityContructor"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityConstructorAndMultipleHeadersRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
final String requestUrl = "/response-entity-contructor-multiple-headers";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityConstructorAndHeaders"));
|
||||
assertThat(responseHeaders).containsEntry("Accept", Arrays.asList(MediaType.APPLICATION_JSON.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityBuilderRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/response-entity-builder";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilder"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenResponseEntityBuilderAndHttpHeadersRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/response-entity-builder-with-http-headers";
|
||||
ResponseEntity<String> response = template.getForEntity(SINGLE_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ResponseEntityBuilderWithHttpHeaders"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterWithNoExtraHeaderRequest_thenObtainResponseWithCorrectHeader() {
|
||||
final String requestUrl = "/no-extra-header";
|
||||
ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterWithExtraHeaderRequest_thenObtainResponseWithCorrectHeaders() {
|
||||
final String requestUrl = "/extra-header";
|
||||
ResponseEntity<String> response = template.getForEntity(FILTER_BASE_URL + requestUrl, String.class);
|
||||
HttpHeaders responseHeaders = response.getHeaders();
|
||||
|
||||
assertThat(responseHeaders).isNotEmpty();
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_FILTER_RESPONSE_HEADER, Arrays.asList("Value-Filter"));
|
||||
assertThat(responseHeaders).containsEntry(SERVICE_SINGLE_RESPONSE_HEADER, Arrays.asList("Value-ExtraHeader"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.uribuilder;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
public class SpringUriBuilderIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void constructUri() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit-5").build();
|
||||
|
||||
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructUriEncoded() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/junit 5").build().encode();
|
||||
|
||||
assertEquals("http://www.baeldung.com/junit%205", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructUriFromTemplate() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.baeldung.com").path("/{article-name}").buildAndExpand("junit-5");
|
||||
|
||||
assertEquals("http://www.baeldung.com/junit-5", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void constructUriWithQueryParameter() {
|
||||
UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme("http").host("www.google.com").path("/").query("q={keyword}").buildAndExpand("baeldung");
|
||||
|
||||
assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void expandWithRegexVar() {
|
||||
String template = "/myurl/{name:[a-z]{1,5}}/show";
|
||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(template).build();
|
||||
uriComponents = uriComponents.expand(Collections.singletonMap("name", "test"));
|
||||
|
||||
assertEquals("/myurl/test/show", uriComponents.getPath());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.web.controller.status;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
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.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
|
||||
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.config.MvcConfig;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = MvcConfig.class)
|
||||
@WebAppConfiguration
|
||||
@AutoConfigureWebClient
|
||||
public class ExampleControllerIntegrationTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToController_thenReturnsStatusNotAcceptable() throws Exception {
|
||||
mockMvc.perform(get("/controller")).andExpect(status().isNotAcceptable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestSentToException_thenReturnsStatusForbidden() throws Exception {
|
||||
mockMvc.perform(get("/exception")).andExpect(status().isForbidden());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user