1 package io.pactflow.example.sirenprovider.controllers;
3 import io.pactflow.example.sirenprovider.models.Order;
4 import org.springframework.hateoas.CollectionModel;
5 import org.springframework.hateoas.EntityModel;
6 import org.springframework.hateoas.Link;
7 import org.springframework.hateoas.RepresentationModel;
8 import org.springframework.hateoas.server.ExposesResourceFor;
9 import org.springframework.http.ResponseEntity;
10 import org.springframework.web.bind.annotation.DeleteMapping;
11 import org.springframework.web.bind.annotation.GetMapping;
12 import org.springframework.web.bind.annotation.PathVariable;
13 import org.springframework.web.bind.annotation.PutMapping;
14 import org.springframework.web.bind.annotation.RequestMapping;
15 import org.springframework.web.bind.annotation.RestController;
17 import java.util.Random;
19 import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.afford;
20 import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
21 import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
24 @ExposesResourceFor(Order.class)
25 @RequestMapping(value = "/orders")
26 public class OrderController {
29 public ResponseEntity<RepresentationModel<?>> orders() {
30 Long id = Math.abs(new Random().nextLong());
31 Order order = new Order(id);
32 Link selfLink = actions(order);
33 EntityModel<Order> model = EntityModel.of(order, selfLink);
34 RepresentationModel<?> orders = CollectionModel.of(model);
35 orders.add(linkTo(methodOn(OrderController.class).orders()).withSelfRel());
36 return ResponseEntity.ok(orders);
39 @GetMapping(value = "/{id}")
40 public ResponseEntity<EntityModel<Order>> order(@PathVariable(value = "id", required = true) Long id) {
41 Order order = new Order(id);
42 Link selfLink = actions(order);
43 EntityModel<Order> model = EntityModel.of(order, selfLink);
44 return ResponseEntity.ok(model);
48 public EntityModel<Order> update(@PathVariable(value = "id", required = true) Long id, Order order) {
49 Link selfLink = actions(order);
50 return EntityModel.of(order, selfLink);
53 private Link actions(Order order) {
54 return linkTo(methodOn(OrderController.class).order(order.getId())).withSelfRel()
55 .andAffordance(afford(methodOn(OrderController.class).update(order.getId(), null)))
56 .andAffordance(afford(methodOn(OrderController.class).delete(order.getId())))
57 .andAffordance(afford(methodOn(OrderController.class).changeStatus(order.getId(), null)));
60 @PutMapping("/{id}/status")
61 public EntityModel<Order> changeStatus(@PathVariable(value = "id", required = true) Long id, String status) {
62 Order order = new Order(id);
63 Link selfLink = actions(order);
64 return EntityModel.of(order, selfLink);
67 @DeleteMapping("/{id}")
68 public ResponseEntity<Void> delete(@PathVariable(value = "id", required = true) Long id) {
69 return ResponseEntity.ok().build();