[BAEL-18367] Moving articles from rest-spring-** pt 4

This commit is contained in:
Sjmillington
2019-12-08 10:42:40 +00:00
parent b15d47bc9a
commit 9f9362d458
35 changed files with 190 additions and 562 deletions

View File

@@ -4,12 +4,10 @@ This module contains articles about REST APIs in Spring
## Relevant articles:
- [Guide to UriComponentsBuilder in Spring](https://www.baeldung.com/spring-uricomponentsbuilder)
- [Returning Custom Status Codes from Spring Controllers](https://www.baeldung.com/spring-mvc-controller-custom-http-status-code)
- [Spring RequestMapping](https://www.baeldung.com/spring-requestmapping)
- [Spring and Apache FileUpload](https://www.baeldung.com/spring-apache-file-upload)
- [Test a REST API with curl](https://www.baeldung.com/curl-rest)
- [Best Practices for REST API Error Handling](https://www.baeldung.com/rest-api-error-handling-best-practices)
- [Binary Data Formats in a Spring REST API](https://www.baeldung.com/spring-rest-api-with-binary-data-formats)
### NOTE:

View File

@@ -1,47 +0,0 @@
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;
}
}

View File

@@ -1,55 +0,0 @@
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);
}
}

View File

@@ -1,127 +0,0 @@
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";
}
}

View File

@@ -1,24 +0,0 @@
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();
}
}

View File

@@ -1,10 +0,0 @@
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;
}

View File

@@ -1,82 +0,0 @@
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")));
}
}

View File

@@ -1,44 +0,0 @@
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());
}
}