Fibinger Ádám
2019-03-11 94fead6be729cfb23b657d853c5499709a3d27c4
commit | author | age
94fead 1 package hu.unr.fiber.cardapi.hibernate;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import hu.unr.fiber.cardapi.interfaces.CardInteractorInterface;
7 import hu.unr.fiber.cardapi.interfaces.CardInterface;
8 import hu.unr.fiber.cardapi.rest.RestCard;
9 import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
10 import org.springframework.stereotype.Component;
11
12 @Component
13 public class CardInteractor implements CardInteractorInterface {
14
15     private CardRepository cardRepository;
16
17     CardInteractor(CardRepository cardRepository) {
18         this.cardRepository = cardRepository;
19     }
20
21     @Override
22     public List<CardInterface> getCardList() {
23
24         List<Card> cardList = this.cardRepository.findAll();
25         List<CardInterface> restCardList = new ArrayList<>();
26
27         for (Card card : cardList) {
28             RestCard ce = new RestCard(card.getId());
29             restCardList.add(ce.update(card));
30         }
31
32         return restCardList;
33     }
34
35     @Override
36     public CardInterface getCardById(long id) throws CardNotFoundException {
37         if (!this.cardRepository.existsById(id)) {
38             throw new CardNotFoundException("No such card with id: #"+ id);
39         }
40
41         Card c = this.cardRepository.getOne(id);
42         RestCard ce = new RestCard(c.getId());
43
44         return ce.update(c);
45     }
46
47     @Override
48     public void delete(long id) throws CardNotFoundException {
49         try {
50             Card c = this.cardRepository.getOne(id);
51             this.cardRepository.delete(c);
52             this.cardRepository.flush();
53         } catch (JpaObjectRetrievalFailureException e) {
54             throw new CardNotFoundException(e.getMessage());
55         }
56     }
57
58     @Override
59     public CardInterface update(long id, CardInterface updatedCard) throws CardInvalidUpdateException, CardNotFoundException {
60         if (updatedCard.validId() && (updatedCard.getId() != id)) {
61             throw new CardInvalidUpdateException("Card ID cannot be changed! ", updatedCard);
62         }
63
64         if (this.getCardByNumber(updatedCard.getNumber()) != null) {
65             throw new CardInvalidUpdateException("Given card number already exists", updatedCard);
66         }
67
68         this.cardRepository.saveAndFlush((Card) updatedCard);
69
70         return this.getCardById(updatedCard.getId());
71     }
72
73     private Card getCardByNumber(String number) {
74
75         Long id = cardRepository.findIdByNumber(number);
76
77         if (id == null) {
78             return null;
79         }
80
81         return this.cardRepository.getOne(id);
82     }
83 }