Fibinger Ádám
2019-03-11 94fead6be729cfb23b657d853c5499709a3d27c4
src/main/java/hu/unr/fiber/cardapi/CardController.java
@@ -1,95 +1,120 @@
package hu.unr.fiber.cardapi;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import hu.unr.fiber.cardapi.hibernate.CardNotFoundException;
import hu.unr.fiber.cardapi.interfaces.CardInterface;
import hu.unr.fiber.cardapi.hibernate.CardInteractor;
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;
import org.springframework.web.server.ResponseStatusException;
@RestController
public class CardController {
    Logger logger = LoggerFactory.getLogger(CardController.class);
    private CardInteractor cardService;
    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"));
    CardController(CardInteractor cS) {
        this.cardService = cS;
    }
    @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} )";
        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("/cards called, responded with " + cardList.size() + " items.");
        return cardList;
    public ResponseEntity<List<CardInterface>> cards() {
        logger.info("GET /cards called, responded with items.");
        List<CardInterface> cardList = cardService.getCardList();
        return ResponseEntity.ok().body(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
    public ResponseEntity<CardInterface> getCard(@PathVariable("id") long id) {
        logger.info("GET /card/" + id + " called.");
        try {
            CardInterface card = this.cardService.getCardById(id);
            return ResponseEntity.ok().body(card);
        } catch (CardNotFoundException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No such card with id: #" + id);
        }
    }
    private Card getCardByID(long id) {
        for (Card card : cardList) {
            if (card.getId() == id) {
                return card;
            }
    @DeleteMapping(value = "/card/{id}")
    public ResponseEntity<String> deleteCard(@PathVariable("id") long id) {
        logger.info("DELETE /card/" + id + " called");
        try {
            this.cardService.delete(id);
        } catch (CardNotFoundException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No such card with id: #" + id, e);
        }
        return null;
        return ResponseEntity.ok().body("OK");
    }
/*
    @PostMapping(value = "/card/{id}")
    public ResponseEntity<String> updateCard(@PathVariable("id") long id, @RequestBody RestCard updatedCardEntity, UriComponentsBuilder ucBuilder) {
    private Card getCardByNumber(String number) {
        for (Card card : cardList) {
            if (card.getNumber().equals(number)) {
                return card;
            }
        logger.info("POST /card/" + id + " called, card update.");
        try {
            this.cardService.update(id, updatedCardEntity);
        } catch (CardInvalidUpdateException e){
        }
        return null;
        RestCard originalCardEntity = this.cardRepository.getOne(id);
        if (originalCardEntity.equals(updatedCardEntity)) {
            return ResponseEntity.accepted().body("Update has no changes.");
        }
        //card number updated, we have to check if its already exists
        if (!originalCardEntity.getNumber().equals(updatedCardEntity.getNumber()) && this.getCardByNumber(updatedCardEntity.getNumber()) != null) {
            logger.error("Unable to update card with id {}. A different RestCard with number {} already exist", originalCardEntity.getId(), updatedCardEntity.getNumber());
            return ResponseEntity.status(HttpStatus.CONFLICT).body("RestCard with number " + updatedCardEntity.getNumber() + " already exists.");
        }
        originalCardEntity.update(updatedCardEntity);
        this.cardRepository.flush();
        return ResponseEntity.accepted().body("OK");
    }
    private RestCard getCardByNumber(String number) {
        Long id = cardRepository.findIdByNumber(number);
        if (id == null) {
            return null;
        }
        return cardRepository.getOne(id);
    }
    @PostMapping(value = "/card")
    public ResponseEntity<String> createCard(@RequestBody Card card, UriComponentsBuilder ucBuilder) {
        logger.info("Creating Card : {}", card);
    public ResponseEntity<String> createCard(@RequestBody RestCard card, UriComponentsBuilder ucBuilder) {
        logger.info("Creating RestCard : {}", 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).build();
            logger.error("Unable to create. A RestCard with number {} already exist", card.getNumber());
            return ResponseEntity.status(HttpStatus.CONFLICT).body("RestCard with number " + card.getNumber() + " already exists.");
        }
        long nextId = new Random().nextLong();
        this.cardRepository.saveAndFlush(card);
        while (this.getCardByID(nextId) != null) {
            nextId = new Random().nextLong();
        }
        URI newCardURI = ucBuilder.path("/card/{id}").buildAndExpand(card.getId()).toUri();
        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);
        return ResponseEntity
                .created(newCardURI)
                .body(newCardURI.toString());
    }
    */
}