Moved Spring HATEOAS article to spring-boot-rest module

This commit is contained in:
Ger Roza
2019-04-16 17:13:15 -03:00
parent 3d193b8ebf
commit f391ddf462
12 changed files with 148 additions and 43 deletions
@@ -0,0 +1,60 @@
package com.baeldung.persistence.model;
import java.util.Map;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class Customer extends ResourceSupport {
private String customerId;
private String customerName;
private String companyName;
private Map<String, Order> orders;
public Customer() {
super();
}
public Customer(final String customerId, final String customerName, final String companyName) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.companyName = companyName;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(final String customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(final String customerName) {
this.customerName = customerName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(final String companyName) {
this.companyName = companyName;
}
public Map<String, Order> getOrders() {
return orders;
}
public void setOrders(final Map<String, Order> orders) {
this.orders = orders;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.persistence.model;
import org.springframework.hateoas.ResourceSupport;
public class Order extends ResourceSupport {
private String orderId;
private double price;
private int quantity;
public Order() {
super();
}
public Order(final String orderId, final double price, final int quantity) {
super();
this.orderId = orderId;
this.price = price;
this.quantity = quantity;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(final String orderId) {
this.orderId = orderId;
}
public double getPrice() {
return price;
}
public void setPrice(final double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(final int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", price=" + price + ", quantity=" + quantity + "]";
}
}
@@ -0,0 +1,13 @@
package com.baeldung.services;
import java.util.List;
import com.baeldung.persistence.model.Customer;
public interface CustomerService {
List<Customer> allCustomers();
Customer getCustomerDetail(final String id);
}
@@ -0,0 +1,40 @@
package com.baeldung.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.persistence.model.Customer;
@Service
public class CustomerServiceImpl implements CustomerService {
private HashMap<String, Customer> customerMap;
public CustomerServiceImpl() {
customerMap = new HashMap<>();
final Customer customerOne = new Customer("10A", "Jane", "ABC Company");
final Customer customerTwo = new Customer("20B", "Bob", "XYZ Company");
final Customer customerThree = new Customer("30C", "Tim", "CKV Company");
customerMap.put("10A", customerOne);
customerMap.put("20B", customerTwo);
customerMap.put("30C", customerThree);
}
@Override
public List<Customer> allCustomers() {
return new ArrayList<>(customerMap.values());
}
@Override
public Customer getCustomerDetail(final String customerId) {
return customerMap.get(customerId);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.services;
import java.util.List;
import com.baeldung.persistence.model.Order;
public interface OrderService {
List<Order> getAllOrdersForCustomer(String customerId);
Order getOrderByIdForCustomer(String customerId, String orderId);
}
@@ -0,0 +1,59 @@
package com.baeldung.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Order;
@Service
public class OrderServiceImpl implements OrderService {
private HashMap<String, Customer> customerMap;
private HashMap<String, Order> customerOneOrderMap;
private HashMap<String, Order> customerTwoOrderMap;
private HashMap<String, Order> customerThreeOrderMap;
public OrderServiceImpl() {
customerMap = new HashMap<>();
customerOneOrderMap = new HashMap<>();
customerTwoOrderMap = new HashMap<>();
customerThreeOrderMap = new HashMap<>();
customerOneOrderMap.put("001A", new Order("001A", 150.00, 25));
customerOneOrderMap.put("002A", new Order("002A", 250.00, 15));
customerTwoOrderMap.put("002B", new Order("002B", 550.00, 325));
customerTwoOrderMap.put("002B", new Order("002B", 450.00, 525));
final Customer customerOne = new Customer("10A", "Jane", "ABC Company");
final Customer customerTwo = new Customer("20B", "Bob", "XYZ Company");
final Customer customerThree = new Customer("30C", "Tim", "CKV Company");
customerOne.setOrders(customerOneOrderMap);
customerTwo.setOrders(customerTwoOrderMap);
customerThree.setOrders(customerThreeOrderMap);
customerMap.put("10A", customerOne);
customerMap.put("20B", customerTwo);
customerMap.put("30C", customerThree);
}
@Override
public List<Order> getAllOrdersForCustomer(final String customerId) {
return new ArrayList<>(customerMap.get(customerId).getOrders().values());
}
@Override
public Order getOrderByIdForCustomer(final String customerId, final String orderId) {
final Map<String, Order> orders = customerMap.get(customerId).getOrders();
Order selectedOrder = orders.get(orderId);
return selectedOrder;
}
}
@@ -0,0 +1,79 @@
package com.baeldung.web.controller;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;
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.RestController;
import com.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Order;
import com.baeldung.services.CustomerService;
import com.baeldung.services.OrderService;
@RestController
@RequestMapping(value = "/customers")
@EnableHypermediaSupport(type = HypermediaType.HAL)
public class CustomerController {
@Autowired
private CustomerService customerService;
@Autowired
private OrderService orderService;
@GetMapping("/{customerId}")
public Customer getCustomerById(@PathVariable final String customerId) {
return customerService.getCustomerDetail(customerId);
}
@GetMapping("/{customerId}/{orderId}")
public Order getOrderById(@PathVariable final String customerId, @PathVariable final String orderId) {
return orderService.getOrderByIdForCustomer(customerId, orderId);
}
@GetMapping(value = "/{customerId}/orders", produces = { "application/hal+json" })
public Resources<Order> getOrdersForCustomer(@PathVariable final String customerId) {
final List<Order> orders = orderService.getAllOrdersForCustomer(customerId);
for (final Order order : orders) {
final Link selfLink = linkTo(
methodOn(CustomerController.class).getOrderById(customerId, order.getOrderId())).withSelfRel();
order.add(selfLink);
}
Link link = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel();
Resources<Order> result = new Resources<>(orders, link);
return result;
}
@GetMapping(produces = { "application/hal+json" })
public Resources<Customer> getAllCustomers() {
final List<Customer> allCustomers = customerService.allCustomers();
for (final Customer customer : allCustomers) {
String customerId = customer.getCustomerId();
Link selfLink = linkTo(CustomerController.class).slash(customerId)
.withSelfRel();
customer.add(selfLink);
if (orderService.getAllOrdersForCustomer(customerId)
.size() > 0) {
final Link ordersLink = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId))
.withRel("allOrders");
customer.add(ordersLink);
}
}
Link link = linkTo(CustomerController.class).withSelfRel();
Resources<Customer> result = new Resources<>(allCustomers, link);
return result;
}
}
@@ -0,0 +1,98 @@
package com.baeldung.springhateoas;
import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.hateoas.MediaTypes;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.baeldung.persistence.model.Customer;
import com.baeldung.persistence.model.Order;
import com.baeldung.services.CustomerService;
import com.baeldung.services.OrderService;
import com.baeldung.web.controller.CustomerController;
@RunWith(SpringRunner.class)
@WebMvcTest(CustomerController.class)
public class CustomerControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@MockBean
private CustomerService customerService;
@MockBean
private OrderService orderService;
private static final String DEFAULT_CUSTOMER_ID = "customer1";
private static final String DEFAULT_ORDER_ID = "order1";
@Test
public void givenExistingCustomer_whenCustomerRequested_thenResourceRetrieved() throws Exception {
given(this.customerService.getCustomerDetail(DEFAULT_CUSTOMER_ID))
.willReturn(new Customer(DEFAULT_CUSTOMER_ID, "customerJohn", "companyOne"));
this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$._links").doesNotExist())
.andExpect(jsonPath("$.customerId", is(DEFAULT_CUSTOMER_ID)));
}
@Test
public void givenExistingOrder_whenOrderRequested_thenResourceRetrieved() throws Exception {
given(this.orderService.getOrderByIdForCustomer(DEFAULT_CUSTOMER_ID, DEFAULT_ORDER_ID))
.willReturn(new Order(DEFAULT_ORDER_ID, 1., 1));
this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID + "/" + DEFAULT_ORDER_ID))
.andExpect(status().isOk())
.andExpect(jsonPath("$._links").doesNotExist())
.andExpect(jsonPath("$.orderId", is(DEFAULT_ORDER_ID)));
}
@Test
public void givenExistingCustomerWithOrders_whenOrdersRequested_thenHalResourceRetrieved() throws Exception {
Order order1 = new Order(DEFAULT_ORDER_ID, 1., 1);
List<Order> orders = Collections.singletonList(order1);
given(this.orderService.getAllOrdersForCustomer(DEFAULT_CUSTOMER_ID)).willReturn(orders);
this.mvc.perform(get("/customers/" + DEFAULT_CUSTOMER_ID + "/orders").accept(MediaTypes.HAL_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.orderList[0]._links.self.href",
is("http://localhost/customers/customer1/order1")))
.andExpect(jsonPath("$._links.self.href", is("http://localhost/customers/customer1/orders")));
}
@Test
public void givenExistingCustomer_whenAllCustomersRequested_thenHalResourceRetrieved() throws Exception {
// customers
Customer retrievedCustomer = new Customer(DEFAULT_CUSTOMER_ID, "customerJohn", "companyOne");
List<Customer> customers = Collections.singletonList(retrievedCustomer);
given(this.customerService.allCustomers()).willReturn(customers);
// orders
Order order1 = new Order(DEFAULT_ORDER_ID, 1., 1);
List<Order> orders = Collections.singletonList(order1);
given(this.orderService.getAllOrdersForCustomer(DEFAULT_CUSTOMER_ID)).willReturn(orders);
this.mvc.perform(get("/customers/").accept(MediaTypes.HAL_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(
jsonPath("$._embedded.customerList[0]._links.self.href", is("http://localhost/customers/customer1")))
.andExpect(jsonPath("$._embedded.customerList[0]._links.allOrders.href",
is("http://localhost/customers/customer1/orders")))
.andExpect(jsonPath("$._links.self.href", is("http://localhost/customers")));
}
}