package hu.unr.fiber.cardapi.hibernate;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
|
import hu.unr.fiber.cardapi.interfaces.CardInteractorInterface;
|
import hu.unr.fiber.cardapi.interfaces.CardInterface;
|
import hu.unr.fiber.cardapi.rest.RestCard;
|
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
|
import org.springframework.stereotype.Component;
|
|
@Component
|
public class CardInteractor implements CardInteractorInterface {
|
|
private CardRepository cardRepository;
|
|
CardInteractor(CardRepository cardRepository) {
|
this.cardRepository = cardRepository;
|
}
|
|
@Override
|
public List<CardInterface> getCardList() {
|
|
List<Card> cardList = this.cardRepository.findAll();
|
List<CardInterface> restCardList = new ArrayList<>();
|
|
for (Card card : cardList) {
|
RestCard ce = new RestCard(card.getId());
|
restCardList.add(ce.update(card));
|
}
|
|
return restCardList;
|
}
|
|
@Override
|
public CardInterface getCardById(long id) throws CardNotFoundException {
|
if (!this.cardRepository.existsById(id)) {
|
throw new CardNotFoundException("No such card with id: #"+ id);
|
}
|
|
Card c = this.cardRepository.getOne(id);
|
RestCard ce = new RestCard(c.getId());
|
|
return ce.update(c);
|
}
|
|
@Override
|
public void delete(long id) throws CardNotFoundException {
|
try {
|
Card c = this.cardRepository.getOne(id);
|
this.cardRepository.delete(c);
|
this.cardRepository.flush();
|
} catch (JpaObjectRetrievalFailureException e) {
|
throw new CardNotFoundException(e.getMessage());
|
}
|
}
|
|
@Override
|
public CardInterface update(long id, CardInterface updatedCard) throws CardInvalidUpdateException, CardNotFoundException {
|
if (updatedCard.validId() && (updatedCard.getId() != id)) {
|
throw new CardInvalidUpdateException("Card ID cannot be changed! ", updatedCard);
|
}
|
|
if (this.getCardByNumber(updatedCard.getNumber()) != null) {
|
throw new CardInvalidUpdateException("Given card number already exists", updatedCard);
|
}
|
|
this.cardRepository.saveAndFlush((Card) updatedCard);
|
|
return this.getCardById(updatedCard.getId());
|
}
|
|
private Card getCardByNumber(String number) {
|
|
Long id = cardRepository.findIdByNumber(number);
|
|
if (id == null) {
|
return null;
|
}
|
|
return this.cardRepository.getOne(id);
|
}
|
}
|