package hu.unr.fiber.cardapi;
|
|
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.HttpHeaders;
|
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("/index called.");
|
return "Hello world! Hateoas helyett: (/cards GET /card/{id} POST /card/{id} PUT /card/{id} DELETE /card/{id} )";
|
}
|
|
@GetMapping("/cards")
|
public List<Card> cards() {
|
logger.info("/cards called, responded with " + cardList.size() + " items.");
|
return cardList;
|
}
|
|
@GetMapping(value = "/card/{id}")
|
public ResponseEntity<Card> getUser(@PathVariable("id") long id) {
|
logger.info("/card/" + id + " called");
|
return Optional
|
.ofNullable(this.getCardByID(id))
|
.map(card -> ResponseEntity.ok().body(card)) //200 OK
|
.orElseGet(() -> ResponseEntity.notFound().build()); //404 Not found
|
}
|
|
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);
|
|
if (this.getCardByNumber(card.getNumber()) != null) {
|
logger.error("Unable to create. A Card with number {} already exist", card.getNumber());
|
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
}
|
|
long nextId = new Random().nextLong();
|
|
while (this.getCardByID(nextId) != null) {
|
nextId = new Random().nextLong();
|
}
|
|
card.setId(nextId);
|
|
cardList.add(card);
|
|
HttpHeaders headers = new HttpHeaders();
|
headers.setLocation(ucBuilder.path("/card/{id}").buildAndExpand(card.getId()).toUri());
|
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
|
}
|
|
}
|