Fibinger Ádám
2019-02-20 ca273270cd55e594c472566ba9a351b6dcaaa3c6
commit | author | age
9b7a17 1 package hu.unr.fiber.cardapi;
2
ca2732 3 import java.net.URI;
9b7a17 4 import java.util.ArrayList;
5 import java.util.List;
6 import java.util.Optional;
7 import java.util.Random;
8
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11 import org.springframework.http.HttpStatus;
12 import org.springframework.http.ResponseEntity;
13 import org.springframework.web.bind.annotation.*;
14 import org.springframework.web.util.UriComponentsBuilder;
15
16 @RestController
17 public class CardController {
18     Logger logger = LoggerFactory.getLogger(CardController.class);
19
20     protected List<Card> cardList = new ArrayList<>();
21
22     public CardController() {
23         cardList.add(new Card(1, "Első kártya", "1"));
24         cardList.add(new Card(2, "Második kártya", "2"));
25         cardList.add(new Card(5, "Harmadik kártya", "4"));
26         cardList.add(new Card(8, "Tízezer egyszázadik kártya", "10100"));
27     }
28
29     @GetMapping("/")
30     public String index() {
ca2732 31         logger.info("GET /index called.");
32         return "Hateoas helyett: (/cards GET /card/{id} POST /card/{id} PUT /card/{id} DELETE /card/{id} )";
9b7a17 33     }
34
35     @GetMapping("/cards")
36     public List<Card> cards() {
ca2732 37         logger.info("GET /cards called, responded with " + cardList.size() + " items.");
9b7a17 38         return cardList;
39     }
40
41     @GetMapping(value = "/card/{id}")
ca2732 42     public ResponseEntity<Card> getCard(@PathVariable("id") long id) {
43         logger.info("GET /card/" + id + " called.");
9b7a17 44         return Optional
45                 .ofNullable(this.getCardByID(id))
46                 .map(card -> ResponseEntity.ok().body(card))          //200 OK
47                 .orElseGet(() -> ResponseEntity.notFound().build());  //404 Not found
ca2732 48     }
49
50     @DeleteMapping(value = "/card/{id}")
51     public ResponseEntity<String> deleteCard(@PathVariable("id") long id) {
52         logger.info("DELETE /card/" + id + " called");
53
54         return Optional
55                 .ofNullable(this.getCardByID(id))
56                 .map(
57                         card -> {
58                             this.cardList.remove(card);
59                             return ResponseEntity.ok().body("OK");
60                         }
61                 )
62                 .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body("No card available with id: "+ id));
63     }
64
65     @PostMapping(value = "/card/{id}")
66     public ResponseEntity<String> updateCard(@PathVariable("id") long id, @RequestBody Card updatedCard, UriComponentsBuilder ucBuilder) {
67
68         logger.info("POST /card/"+ id + " called, card update.");
69
70         if (updatedCard.validId() && (updatedCard.getId() != id))
71         {
72             return ResponseEntity
73                     .badRequest()
74                     .body("Id field cannot be modified.");
75         }
76
77         Card originalCard = this.getCardByID(id);
78
79         if (originalCard.equals(updatedCard)) {
80             return ResponseEntity.accepted().body("Update has no changes.");
81         }
82
83         //card number updated, we have to check if its already exists
84         if (!originalCard.getNumber().equals(updatedCard.getNumber()) && this.getCardByNumber(updatedCard.getNumber()) != null) {
85             logger.error("Unable to update card with id {}. A different Card with number {} already exist", originalCard.getId(), updatedCard.getNumber());
86             return ResponseEntity.status(HttpStatus.CONFLICT).body("Card with number " + updatedCard.getNumber() + " already exists.");
87         }
88
89         originalCard.update(updatedCard);
90
91         return ResponseEntity.accepted().body("OK");
9b7a17 92     }
93
94     private Card getCardByID(long id) {
95         for (Card card : cardList) {
96             if (card.getId() == id) {
97                 return card;
98             }
99         }
100
101         return null;
102     }
103
104     private Card getCardByNumber(String number) {
105         for (Card card : cardList) {
106             if (card.getNumber().equals(number)) {
107                 return card;
108             }
109         }
110
111         return null;
112     }
113
114
115     @PostMapping(value = "/card")
116     public ResponseEntity<String> createCard(@RequestBody Card card, UriComponentsBuilder ucBuilder) {
ca2732 117         logger.info("Creating Card : {}", card.getNumber());
9b7a17 118
119         if (this.getCardByNumber(card.getNumber()) != null) {
120             logger.error("Unable to create. A Card with number {} already exist", card.getNumber());
ca2732 121             return ResponseEntity.status(HttpStatus.CONFLICT).body("Card with number "+ card.getNumber() + " already exists.");
9b7a17 122         }
123
ca2732 124         long nextId = 1;
9b7a17 125
126         while (this.getCardByID(nextId) != null) {
ca2732 127             nextId++;
9b7a17 128         }
129
130         card.setId(nextId);
131
132         cardList.add(card);
133
ca2732 134         URI newCardURI = ucBuilder.path("/card/{id}").buildAndExpand(card.getId()).toUri();
135
136         return ResponseEntity
137                 .created(newCardURI)
138                 .body(newCardURI.toString());
9b7a17 139     }
140
141 }