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