I'm pretty new to java, trying write some unit test for my code. But stuck on one of them.
this is method i want test :
public Reservation findSpecificReservation(Long id) throws NullPointerException{
Reservation reservation = null;
Optional<Reservation> byId = iReservationRepository.findById(id);
if(byId.isPresent()){
reservation = byId.get();
}
return reservation;
}
those are variables mock and setup :
private IReservationService iReservationService;
#Mock
private IReservationRepository repository;
#Before
public void setUp() {
initMocks(this);
iReservationService = new ReservationServices(repository);
}
and test looks like :
#Test
public void shouldFindReservation() {
Long id = 1L;
Reservation expected = getDefaultReservation();
when(iReservationService.findSpecificReservation(id)).thenReturn(getDefaultReservation());
Reservation actual = iReservationService.findSpecificReservation(id);
Assert.assertThat(expected, is(actual));
}
My test throws nullpointer exception in the lane where im trying do when thenReturn, ireservationService.findSpecificReservatin(id) throws it.
Can someone please let me know what im doing wrong ?
Im begginer in programming and will be glad if you can go soft on me Thanks !
edit adding whole classes :
package com.hotelReservation.hotelReservation.services;
import com.hotelReservation.hotelReservation.domain.ReservationStatusResponse;
import com.hotelReservation.hotelReservation.entity.Reservation;
import com.hotelReservation.hotelReservation.entity.User;
import com.hotelReservation.hotelReservation.repository.IReservationRepository;
import com.hotelReservation.hotelReservation.repository.IRoomRepository;
import com.hotelReservation.hotelReservation.repository.IUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Service
public class ReservationServices implements IReservationService {
private IReservationRepository iReservationRepository;
private IRoomRepository iRoomRepository;
private IUserRepository iUserRepository;
#Autowired
public ReservationServices(IReservationRepository iReservationRepository) {
this.iReservationRepository = iReservationRepository;
this.iRoomRepository = iRoomRepository;
this.iUserRepository = iUserRepository;
}
#Override
public ReservationStatusResponse addReservation(LocalDate begin, LocalDate end, Long roomId, Long userId, String breakfast, String diner, String rentCar, int adultsForReservation) {
PriceCounter priceCounter = new PriceCounter();
int days = 0;
if (end.isAfter(begin)) {
days = begin.until(end).getDays();
}
int price = priceCounter.calculatePrice(breakfast, diner, rentCar, days, adultsForReservation);
Reservation newReservation = Reservation.builder()
.begin(begin)
.end(end)
.roomForReservation(iRoomRepository.findById(roomId).get())
.user(iUserRepository.findById(userId).get())
.breakfast(breakfast)
.dinner(diner)
.rentCar(rentCar)
.adultsForReservation(adultsForReservation)
.price(price)
.build();
ReservationStatusResponse reservationStatusResponse = checkIsReservationDatesAreNotTaken(newReservation.getRoomForReservation()
.getId(), newReservation.getBegin(), newReservation.getEnd());
if (reservationStatusResponse.isPossible()) {
iReservationRepository.save(newReservation);
}
return reservationStatusResponse;
}
#Override
public void cancelReservation(Long id) {
iReservationRepository.deleteById(id);
}
public List<Reservation> findAllReservationOfSpecificUser(Long id) {
List<Reservation> allByUserId = iReservationRepository.findAllByUserId(id);
return new ArrayList<>(allByUserId);
}
public Reservation findSpecificReservation(Long id) throws NullPointerException {
Reservation reservation = null;
Optional<Reservation> byId = iReservationRepository.findById(id);
if (byId.isPresent()) {
reservation = byId.get();
}
return reservation;
}
public List<Reservation> findAllReservationsOnRoom(Long roomId) {
return iReservationRepository.findReservationsByRoom(roomId);
}
#Override
public ReservationStatusResponse checkIsReservationDatesAreNotTaken(Long roomId, LocalDate begin, LocalDate end) {
ReservationStatusResponse reservationStatusResponse = new ReservationStatusResponse();
if (begin.isAfter(end) || begin.isBefore(LocalDate.now())) {
reservationStatusResponse.setPossible(false);
reservationStatusResponse.setReason("Begin date is after end date or before today !");
return reservationStatusResponse;
}
int newReservationPeriod = begin.until(end).getDays();
List<LocalDate> newReservationDates = new ArrayList<>();
List<LocalDate> takenReservationDates = new ArrayList<>();
for (int i = 0; i <= newReservationPeriod; i++) {
newReservationDates.add(begin.plusDays(i));
}
List<Reservation> allReservationsOnRoom = findAllReservationsOnRoom(roomId);
for (Reservation r :
allReservationsOnRoom) {
int existingReservationPeriod = r.getBegin().until(r.getEnd()).getDays();
for (int i = 0; i <= existingReservationPeriod; i++) {
takenReservationDates.add(r.getBegin().plusDays(i));
}
for (LocalDate l :
takenReservationDates) {
for (LocalDate lo :
newReservationDates) {
if (l.isEqual(lo)) {
reservationStatusResponse.setReason("Date is taken");
reservationStatusResponse.setPossible(false);
return reservationStatusResponse;
}
}
}
}
reservationStatusResponse.setPossible(true);
reservationStatusResponse.setReason("Possible");
return reservationStatusResponse;
}
#Override
public List<Reservation> findAll() {
return iReservationRepository.findAll();
}
}
test class :
package com.hotelReservation.hotelReservation.services;
import com.hotelReservation.hotelReservation.domain.ReservationStatusResponse;
import com.hotelReservation.hotelReservation.entity.Reservation;
import com.hotelReservation.hotelReservation.entity.Room;
import com.hotelReservation.hotelReservation.repository.IReservationRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class ReservationServicesTest {
private IReservationService iReservationService;
#Mock
private IReservationRepository repository;
#Before
public void setUp() {
initMocks(this);
iReservationService = new ReservationServices(repository);
}
#Test
public void ShouldDeleteReservationById() {
Long id = 12L;
Mockito.doNothing().when(repository).deleteById(id);
iReservationService.cancelReservation(id);
Mockito.verify(repository, Mockito.times(1)).deleteById(id);
}
#Test
public void shouldFindReservation() {
Long id = 1L;
Reservation expected = getDefaultReservation();
when(iReservationService.findSpecificReservation(id)).thenReturn(getDefaultReservation());
Reservation actual = iReservationService.findSpecificReservation(id);
Assert.assertThat(expected, is(actual));
}
#Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnFindingReservationWithDoesntExist() {
Long id = 1L;
iReservationService.findSpecificReservation(id);
}
#Test
public void shouldReturnListOfReservations() {
Long id = 1L;
List<Reservation> reservationListFromDb = getReservationDatesListFromDb();
when(iReservationService.findAllReservationsOnRoom(id)).thenReturn(reservationListFromDb);
List<Reservation> actual = iReservationService.findAllReservationsOnRoom(id);
Assert.assertArrayEquals(reservationListFromDb.toArray(), actual.toArray());
}
private List<Reservation> getReservationDatesListFromDb() {
Reservation first = Reservation.builder()
.begin(LocalDate.of(2018, 05, 01))
.end(LocalDate.of(2018, 05, 03))
.build();
Reservation second = Reservation.builder()
.begin(LocalDate.of(2017, 05, 01))
.end(LocalDate.of(2017, 05, 03))
.build();
return Arrays.asList(first, second);
}
private Reservation getDefaultReservation() {
return Reservation.builder()
.begin(LocalDate.of(2018, 7, 23))
.end(LocalDate.of(2018, 7, 29))
.reservationId(1234L)
.roomForReservation(getDefaultRoom())
.rentCar("NO")
.breakfast("NO")
.dinner("NO")
.adultsForReservation(2)
.build();
}
public Room getDefaultRoom() {
return Room.builder()
.howManyPeople(2)
.id(12L)
.roomClass("Hobbit")
.build();
}
}
You forgot the #InjectMocks over iReservationService.
#InjectMocks
private IReservationService iReservationService;
Also there's no need for doing
iReservationService = new ReservationServices(repository);
in your setup() method.
And you should be mocking the calls of repository and not the iReservationService itself.
Related
I'm using the Gson library and jakarta. Although I have been able to use the conversion in CarrinhoResource.java as below, my ClienteTest.java cannot use the String content (already in json) inside the cart. I cant run my test a just only message into my intellij is (Cannot resolve method 'fromJson(java.lang.String)').
Can someone help me?
Class CarrinhoResource.java
package br.com.alura.loja.resource;
import br.com.alura.loja.dao.CarrinhoDAO;
import br.com.alura.loja.modelo.Carrinho;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
#Path("/v1/carrinhos")
public class CarrinhoResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String busca(){
Carrinho carrinho = new CarrinhoDAO().busca(1L);
return carrinho.toJson();
}
}
Carrinho.java
package br.com.alura.loja.modelo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
public class Carrinho {
private List<Produto> produtos = new ArrayList<Produto>();
private String rua;
private String cidade;
private long id;
public Carrinho adiciona(Produto produto) {
produtos.add(produto);
return this;
}
public Carrinho para(String rua, String cidade) {
this.rua = rua;
this.cidade = cidade;
return this;
}
public Carrinho setId(long id) {
this.id = id;
return this;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public long getId() {
return id;
}
public void remove(long id) {
for (Iterator iterator = produtos.iterator(); iterator.hasNext();) {
Produto produto = (Produto) iterator.next();
if(produto.getId() == id) {
iterator.remove();
}
}
}
public void troca(Produto produto) {
remove(produto.getId());
adiciona(produto);
}
public void trocaQuantidade(Produto produto) {
for (Iterator iterator = produtos.iterator(); iterator.hasNext();) {
Produto p = (Produto) iterator.next();
if(p.getId() == produto.getId()) {
p.setQuantidade(produto.getQuantidade());
return;
}
}
}
public List<Produto> getProdutos() {
return produtos;
}
public String toJson() {
return new Gson().toJson(this);
}
}
ClienteTest.java
package br.com.alura.loja;
import br.com.alura.loja.modelo.Carrinho;
import com.google.gson.*;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import org.junit.Assert;
import org.junit.Test;
public class ClienteTest {
#Test
public void testaConexaoServidor() {
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8085");
String conteudo = target.path("/v1/carrinhos").request().get(String.class);
Carrinho carrinho = (Carrinho) new Gson().fromJson(conteudo); **//Cannot resolve method 'fromJson(java.lang.String)'/**
System.out.println(carrinho);
Assert.assertEquals("Rua Vergueiro, 3185", carrinho.getRua());
}
}
Carrinho carrinho = (Carrinho) new Gson().fromJson(conteudo); **//Cannot resolve method 'fromJson(java.lang.String)'/**
The reason for this is that there is no Gson.fromJson(String) method, see the Gson class documentation. For deserialization Gson needs to know which type you are expecting, so all fromJson methods have a second parameter representing the type.
You can simply change your code to:
Carrinho carrinho = new Gson().fromJson(conteudo, Carrinho.class);
Well, my issue is related to when I try to save an entity (Parade) which has a collection of other entity (AcmeFloat) using the corresponding default CRUD method in convenient repository (the code is attached below). When it reaches the save() method, it throws an exception.
I tried to save the pertinent entities of AcmeFloat class which need to be updated by hand, but, whatever I do (whether save first the Parade updated and later update and save each AcmeFloat or inside out) raises an exception.
So I went into Stack Overflow and the solution I found is putting a 'cascade=CascadeType.ALL' inside the #ManyToMany anotation, without success. I tried also to do both things, which also fails.
Here is the code:
Parade (Domain Class):
package domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Access(AccessType.PROPERTY)
public class Parade extends DomainEntity {
// Fields -----------------------------------------------------------------
private String title;
private String description;
private Date moment;
private String ticker;
private boolean isDraft;
// Relationships ----------------------------------------------------------
private Brotherhood brotherhood;
private Collection<AcmeFloat> acmeFloats;
// Field access methods ---------------------------------------------------
#NotBlank
public String getTitle() {
return this.title;
}
public void setTitle(final String title) {
this.title = title;
}
#NotBlank
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
public Date getMoment() {
return this.moment;
}
public void setMoment(final Date moment) {
this.moment = moment;
}
#NotBlank
#Pattern(regexp = "^([\\d]){6}-([A-Z]){5}$")
#Column(unique = true)
public String getTicker() {
return this.ticker;
}
public void setTicker(final String ticker) {
this.ticker = ticker;
}
#Basic
public boolean getIsDraft() {
return this.isDraft;
}
public void setIsDraft(final boolean isDraft) {
this.isDraft = isDraft;
}
// Relationship access methods --------------------------------------------
#Valid
#ManyToOne(optional = true)
public Brotherhood getBrotherhood() {
return this.brotherhood;
}
public void setBrotherhood(final Brotherhood brotherhood) {
this.brotherhood = brotherhood;
}
#Valid
#ManyToMany(mappedBy = "parades", cascade = CascadeType.ALL)
public Collection<AcmeFloat> getAcmeFloats() {
return new ArrayList<AcmeFloat>(this.acmeFloats);
}
public void setAcmeFloats(final Collection<AcmeFloat> acmeFloats) {
this.acmeFloats = acmeFloats;
}
}
AcmeFloat (Domain Class):
package domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
#Entity
#Access(AccessType.PROPERTY)
public class AcmeFloat extends DomainEntity {
// Fields -----------------------------------------------------------------
private String title;
private String description;
private List<String> pictures;
// Relationships ----------------------------------------------------------
private Collection<Parade> parades;
private Brotherhood brotherhood;
// Field access methods ---------------------------------------------------
#NotNull
#NotBlank
public String getTitle() {
return this.title;
}
public void setTitle(final String title) {
this.title = title;
}
#NotNull
#NotBlank
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
//Optional
//#URL
#NotNull
#ElementCollection
public List<String> getPictures() {
return this.pictures;
}
public void setPictures(final List<String> pictures) {
this.pictures = pictures;
}
// Relationship access methods --------------------------------------------
#ManyToMany(cascade = CascadeType.ALL)
#Valid
public Collection<Parade> getParades() {
return this.parades;
}
public void setParades(final Collection<Parade> parades) {
this.parades = new ArrayList<Parade>(parades);
}
#ManyToOne
#Valid
public Brotherhood getBrotherhood() {
return this.brotherhood;
}
public void setBrotherhood(final Brotherhood brotherhood) {
this.brotherhood = brotherhood;
}
}
ParadeForm (Form Object):
package forms;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;
import domain.AcmeFloat;
public class ParadeForm {
// Fields -----------------------------------------------------------------
private int id;
private String title;
private String description;
private Date moment;
// Relationships ----------------------------------------------------------
private Collection<AcmeFloat> acmeFloats;
// Field access methods ---------------------------------------------------
#Range(min = 0)
public int getId() {
return this.id;
}
public void setId(final int id) {
this.id = id;
}
#NotBlank
public String getTitle() {
return this.title;
}
public void setTitle(final String title) {
this.title = title;
}
#NotBlank
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
public Date getMoment() {
return this.moment;
}
public void setMoment(final Date moment) {
this.moment = moment;
}
// Relationship access methods --------------------------------------------
#NotNull
public Collection<AcmeFloat> getAcmeFloats() {
return this.acmeFloats;
}
public void setAcmeFloats(final Collection<AcmeFloat> acmeFloats) {
this.acmeFloats = acmeFloats;
}
}
ParadeRepository:
package repositories;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Parade;
#Repository
public interface ParadeRepository extends JpaRepository<Parade, Integer> {
#Query("select p from Parade p where p.ticker like ?1")
List<Parade> findByTicker(String ticker);
#Query("select p from Parade p where p.moment < ?1 and p.isDraft = false")
List<Parade> findBeforeDate(Date date);
#Query("select p from Parade p where p.isDraft = false")
List<Parade> findAllFinal();
#Query("select p from Parade p where p.isDraft = false and brotherhood.userAccount.id = ?1")
List<Parade> findAllFinalByBrotherhoodAccountId(int id);
#Query("select p from Parade p where brotherhood.userAccount.id = ?1")
List<Parade> findAllByBrotherhoodAccountId(int id);
#Query("select p from Parade p join p.brotherhood.enrolments e where e.member.id= ?1")
List<Parade> findPossibleMemberParades(int id);
}
AcmeFloatRepository:
package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.AcmeFloat;
#Repository
public interface AcmeFloatRepository extends JpaRepository<AcmeFloat, Integer> {
#Query("select f from AcmeFloat f where f.brotherhood.userAccount.id = ?1")
Collection<AcmeFloat> findAcmeFloats(int principalId);
}
ParadeService:
package services;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.ParadeRepository;
import security.LoginService;
import domain.AcmeFloat;
import domain.Parade;
import forms.ParadeForm;
#Service
#Transactional
public class ParadeService {
////////////////////////////////////////////////////////////////////////////////
// Managed repository
#Autowired
private ParadeRepository paradeRepository;
////////////////////////////////////////////////////////////////////////////////
// Supporting services
#Autowired
private BrotherhoodService brotherhoodService;
////////////////////////////////////////////////////////////////////////////////
// Supporting services
#Autowired
private Validator validator;
////////////////////////////////////////////////////////////////////////////////
// Ticker generation fields
private static final String TICKER_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int TICKER_LENGTH = 5;
private final Random random = new Random();
////////////////////////////////////////////////////////////////////////////////
// Constructors
public ParadeService() {
super();
}
////////////////////////////////////////////////////////////////////////////////
// CRUD methods
public Parade create() {
final Parade parade = new Parade();
parade.setBrotherhood(this.brotherhoodService.findByUserAccountId(LoginService.getPrincipal().getId()));
parade.setAcmeFloats(new ArrayList<AcmeFloat>());
parade.setIsDraft(true);
parade.setDescription("");
parade.setTitle("");
if (parade.getTicker() == null || parade.getTicker().isEmpty()) {
final Calendar calendar = new GregorianCalendar();
String dateString = "";
dateString += String.format("%02d", calendar.get(Calendar.YEAR) % 100);
dateString += String.format("%02d", calendar.get(Calendar.MONTH) + 1);
dateString += String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH));
dateString += "-";
String ticker;
do {
ticker = dateString;
for (int i = 0; i < ParadeService.TICKER_LENGTH; ++i)
ticker += ParadeService.TICKER_ALPHABET.charAt(this.random.nextInt(ParadeService.TICKER_ALPHABET.length()));
} while (this.paradeRepository.findByTicker(ticker).size() > 0);
parade.setTicker(ticker);
}
return parade;
}
public Parade save(final Parade parade) {
Assert.notNull(parade);
//final Parade originalParade = this.paradeRepository.findOne(parade.getId());
//if (originalParade != null)
Assert.isTrue(parade.getIsDraft());
Assert.isTrue(parade.getMoment().after(new Date()));
//TODO: if ticker existe en BBDD, generar nuevo, else, se guarda
return this.paradeRepository.save(parade);
}
public void delete(final Parade parade) {
Assert.notNull(parade);
Assert.isTrue(parade.getIsDraft());
this.paradeRepository.delete(parade);
}
public Parade findOne(final int id) {
return this.paradeRepository.findOne(id);
}
public List<Parade> findAll() {
return this.paradeRepository.findAll();
}
////////////////////////////////////////////////////////////////////////////////
// Ancillary methods
public List<Parade> findWithin30Days() {
final Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, 30);
final Date plus30Days = calendar.getTime();
return this.paradeRepository.findBeforeDate(plus30Days);
}
public List<Parade> findAllByBrotherhoodAccountId(final int id) {
return this.paradeRepository.findAllByBrotherhoodAccountId(id);
}
public List<Parade> findAllFinalByBrotherhoodAccountId(final int id) {
return this.paradeRepository.findAllFinalByBrotherhoodAccountId(id);
}
public List<Parade> findAllFinal() {
return this.paradeRepository.findAllFinal();
}
public List<Parade> findPossibleMemberParades(final int memberId) {
return this.paradeRepository.findPossibleMemberParades(memberId);
}
public Parade reconstruct(final ParadeForm paradeForm, final BindingResult binding) {
Parade result;
if (paradeForm.getId() == 0)
result = this.create();
else
result = this.paradeRepository.findOne(paradeForm.getId());
result.setTitle(paradeForm.getTitle());
result.setDescription(paradeForm.getDescription());
result.setMoment(paradeForm.getMoment());
result.setAcmeFloats(paradeForm.getAcmeFloats());
this.validator.validate(result, binding);
this.paradeRepository.flush();
if (binding.hasErrors())
throw new ValidationException();
return result;
}
}
AcmeFloatService:
package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import repositories.AcmeFloatRepository;
import domain.AcmeFloat;
import domain.Parade;
#Service
#Transactional
public class AcmeFloatService {
////////////////////////////////////////////////////////////////////////////////
// Managed repository
#Autowired
private AcmeFloatRepository acmeFloatRepository;
////////////////////////////////////////////////////////////////////////////////
// Supporting services
////////////////////////////////////////////////////////////////////////////////
// Constructors
public AcmeFloatService() {
super();
}
////////////////////////////////////////////////////////////////////////////////
// CRUD methods
public AcmeFloat create() {
final AcmeFloat result = new AcmeFloat();
// set fields
result.setTitle("");
result.setDescription("");
result.setPictures(new ArrayList<String>());
// set relationships
result.setParades(new ArrayList<Parade>());
result.setBrotherhood(null);
return result;
}
public AcmeFloat save(final AcmeFloat acmeFloat) {
Assert.isTrue(acmeFloat != null);
return this.acmeFloatRepository.save(acmeFloat);
}
public Iterable<AcmeFloat> save(final Iterable<AcmeFloat> acmeFloats) {
Assert.isTrue(acmeFloats != null);
return this.acmeFloatRepository.save(acmeFloats);
}
public void delete(final AcmeFloat acmeFloat) {
Assert.isTrue(acmeFloat != null);
this.acmeFloatRepository.delete(acmeFloat);
}
public void delete(final Iterable<AcmeFloat> acmeFloats) {
Assert.isTrue(acmeFloats != null);
this.acmeFloatRepository.delete(acmeFloats);
}
public AcmeFloat findOne(final int id) {
return this.acmeFloatRepository.findOne(id);
}
public List<AcmeFloat> findAll() {
return this.acmeFloatRepository.findAll();
}
////////////////////////////////////////////////////////////////////////////////
// Ancillary methods
public Collection<AcmeFloat> findAcmeFloats(final int id) {
return this.acmeFloatRepository.findAcmeFloats(id);
}
}
ParadeController:
package controllers;
import java.util.Collection;
import javax.validation.Valid;
import javax.validation.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import security.LoginService;
import security.UserAccount;
import services.AcmeFloatService;
import services.BrotherhoodService;
import services.ParadeService;
import domain.AcmeFloat;
import domain.Brotherhood;
import domain.Parade;
import forms.ParadeForm;
#Controller
#RequestMapping("/parade")
public class ParadeController extends AbstractController {
// Services ---------------------------------------------------------------
#Autowired
private ParadeService paradeService;
#Autowired
private BrotherhoodService brotherhoodService;
#Autowired
private AcmeFloatService acmeFloatService;
// Constructors -----------------------------------------------------------
public ParadeController() {
}
// List -------------------------------------------------------------------
#RequestMapping(value = "/brotherhood/list", method = RequestMethod.GET)
public ModelAndView list() {
final ModelAndView result;
Collection<Parade> parades;
parades = this.paradeService.findAllByBrotherhoodAccountId(LoginService.getPrincipal().getId());
result = new ModelAndView("parade/brotherhood/list");
result.addObject("parades", parades);
result.addObject("requestURI", "parade/brotherhood/list.do");
return result;
}
// Create -----------------------------------------------------------------
#RequestMapping(value = "/brotherhood/create", method = RequestMethod.GET)
public ModelAndView create() {
final ModelAndView result;
Parade parade;
parade = this.paradeService.create();
parade.setIsDraft(true);
result = this.createEditModelAndView(parade, "create");
return result;
}
// Edit -------------------------------------------------------------------
#RequestMapping(value = "/brotherhood/edit", method = RequestMethod.GET)
public ModelAndView edit(#RequestParam final int paradeId) {
ModelAndView result;
Parade parade;
parade = this.paradeService.findOne(paradeId);
Assert.notNull(parade);
result = this.createEditModelAndView(parade, "edit");
return result;
}
// Save -------------------------------------------------------------------
#RequestMapping(value = "/brotherhood/edit", method = RequestMethod.POST, params = "save")
public ModelAndView save(#ModelAttribute("parade") final ParadeForm paradeForm, final BindingResult binding) {
ModelAndView result;
Parade parade;
Parade oldParade;
parade = this.paradeService.reconstruct(paradeForm, binding);
oldParade = this.paradeService.findOne(paradeForm.getId());
try {
for(AcmeFloat f : parade.getAcmeFloats()){
Collection<Parade> parades = f.getParades();
parades.add(parade);
f.setParades(parades);
this.acmeFloatService.save(f);
}
if(parade.getId() != 0){
Collection<AcmeFloat> paradesRemoved = oldParade.getAcmeFloats();
paradesRemoved.removeAll(parade.getAcmeFloats());
for(AcmeFloat f : paradesRemoved){
final Collection<Parade> parades = f.getParades();
parades.remove(parade);
f.setParades(parades);
this.acmeFloatService.save(f);
}
}
this.paradeService.save(parade);
result = new ModelAndView("redirect:list.do");
} catch (final ValidationException oops) {
result = this.createEditModelAndView(parade, "edit");
} catch (final Throwable oops) {
result = this.createEditModelAndView(parade, "parade.commit.error", "edit");
}
return result;
}
/*
final Parade paradeUpdated = this.paradeService.reconstruct(paradeForm, binding);
Collection<AcmeFloat> paradesRemoved = new ArrayList<>();
if (paradeForm.getId() != 0)
paradesRemoved = parade.getAcmeFloats();
if (paradeUpdated.getId() != 0)
paradesRemoved.removeAll(paradeUpdated.getAcmeFloats());
final Parade paradeSaved = this.paradeService.save(paradeUpdated);
for (final AcmeFloat f : paradeUpdated.getAcmeFloats()) {
final Collection<Parade> parades = f.getParades();
parades.add(paradeSaved);
f.setParades(parades);
this.acmeFloatService.save(f);
}
if (paradeUpdated.getId() != 0)
for (final AcmeFloat f : paradesRemoved) {
final Collection<Parade> parades = f.getParades();
parades.remove(parade);
f.setParades(parades);
this.acmeFloatService.save(f);
*/
// Delete -----------------------------------------------------------------
#RequestMapping(value = "/brotherhood/edit", method = RequestMethod.POST, params = "delete")
public ModelAndView delete(final Parade parade, final BindingResult binding) {
ModelAndView result;
try {
this.paradeService.delete(parade);
result = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
result = this.createEditModelAndView(parade, "parade.commit.error", "edit");
}
return result;
}
// Save in Final Mode -----------------------------------------------------
#RequestMapping(value = "/brotherhood/edit", method = RequestMethod.POST, params = "finalMode")
public ModelAndView finalMode(#Valid final Parade parade, final BindingResult binding) {
ModelAndView result;
if (binding.hasErrors())
result = this.createEditModelAndView(parade, "edit");
else
try {
parade.setIsDraft(false);
this.paradeService.save(parade);
result = new ModelAndView("redirect:list.do");
} catch (final Throwable oops) {
result = this.createEditModelAndView(parade, "parade.commit.error", "edit");
}
return result;
}
// Show -------------------------------------------------------------------
#RequestMapping(value = "/public/show", method = RequestMethod.GET)
public ModelAndView show(#RequestParam final int paradeId) {
ModelAndView result;
Parade parade;
parade = this.paradeService.findOne(paradeId);
Assert.notNull(parade);
Assert.isTrue(parade.getIsDraft());
result = new ModelAndView("parade/public/" + "show");
result.addObject("parade", parade);
// result.addObject("messageCode", null);
return result;
}
// Ancillary Methods ------------------------------------------------------
protected ModelAndView createEditModelAndView(final Parade parade, final String method) {
ModelAndView result;
result = this.createEditModelAndView(parade, null, method);
return result;
}
protected ModelAndView createEditModelAndView(final Parade parade, final String messageCode, final String method) {
final ModelAndView result;
final Brotherhood brotherhood;
final Collection<AcmeFloat> acmeFloats;
final UserAccount userAccount = LoginService.getPrincipal();
brotherhood = this.brotherhoodService.findPrincipal();
acmeFloats = this.acmeFloatService.findAcmeFloats(userAccount.getId());
result = new ModelAndView("parade/brotherhood/" + method);
result.addObject("brotherhood", brotherhood);
result.addObject("acmeFloats", acmeFloats);
result.addObject("parade", parade);
result.addObject("messageCode", messageCode);
return result;
}
}
In the Create case, the flow is the next one: When in the create view after filling form and sending, save() method is called in ParadeController. Its input is a ParadeForm object with id=0. "parade" (the new Parade in this case and the updated Parade in case of edition) and "oldParade" (null in this case but the Parade before the update in update case) objects are created and declared anyway. Then, we go into the try/catch. First, it get the parade's acmeFloats in order to update them adding in their parades collection the just created Parade. But, at first attempt of saving, it throws the following thing:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance
Saving first the new Parade gives the same results. I was intended to, in case it is an edition (so the Parade existed before and can have had AcmeFloats), find the AcmeFloats that have been removed from the Parade and update them and then save the Parade. So I needed the oldParade in edit case to check which AcmeFloats I have to remove the Parade from.
Also, I don't know whether I have to do all this thing with the cascade in #ManyToMany, but just saving the Parade once reconstructed, but it doesn't work anyway, so I decided to post that part of the code so that you figure out how would it work without the cascade.
I've been having troubles with this issue for the last month and before. Thanks in advance.
EDIT 1:
When I put a flush() after saving in the repository, it throws the following exception at saving:
org.springframework.orm.jpa.JpaSystemException: Exception occurred inside getter of domain.Parade.acmeFloats; nested exception is org.hibernate.PropertyAccessException: Exception occurred inside getter of domain.Parade.acmeFloats
I'm writing a simple budgeting program that has a budget class with an array of category classes. Each category class can have child category classes. When I try to save the data to an XML file using JAXB, I get the error
com.sun.istack.internal.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML
I have searched on the error and see it is caused by a parent child relationship where the parent references the child and the child references the parent. Most answers are to use #XMLTransient.
My problem is that my Category class does not reference either the budget parent nor the category parent if one exists.
I am new to JAXB, but not Java. I'm using this app as a learning experience for JAXB and also JavaFX.
Below are my Budget and Category classes.
package budget.model;
import java.time.LocalDate;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.DayOfWeek;
import budget.util.LocalDateAdapter;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
#XmlRootElement(name = "budget")
public class Budget {
// default to Sunday
ObjectProperty<DayOfWeek> startOfWeek = new SimpleObjectProperty<DayOfWeek>(DayOfWeek.SUNDAY);
ObjectProperty<LocalDate> startDate = new SimpleObjectProperty<LocalDate>();
IntegerProperty daysBeyondWeek = new SimpleIntegerProperty(3);
IntegerProperty numberOfWeeks = new SimpleIntegerProperty();
ObservableList<Category> categories = FXCollections.observableArrayList();
// startOfWeek
public DayOfWeek getStartOfWeek() {
return this.startOfWeek.getValue();
}
public void setStartOfWeek(DayOfWeek startOfWeek) {
this.startOfWeek.set(startOfWeek);
}
public ObjectProperty<DayOfWeek> startOfWeekProperty() {
return this.startOfWeek;
}
// startDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getStartDate() {
return this.startDate.getValue();
}
public void setStartDate(LocalDate startDate){
this.startDate.set(startDate);
}
public ObjectProperty<LocalDate> startDateProperty() {
return this.startDate;
}
// daysBeyondWeek
public Integer getDaysBeyondWeek() {
return this.daysBeyondWeek.getValue();
}
public void setDaysBeyondWeek(Integer daysBeyondWeek) {
this.daysBeyondWeek.set(daysBeyondWeek);
}
public IntegerProperty daysBeyondWeekProperty() {
return this.daysBeyondWeek;
}
// numberOFWeeks
public Integer getNumberOfWeeks() {
return this.numberOfWeeks.getValue();
}
public void setNumberOfWeeks(Integer numberOfWeeks) {
this.numberOfWeeks.set(numberOfWeeks);
}
public IntegerProperty numberOfWeeksProperty() {
return numberOfWeeks;
}
// categories
public ObservableList<Category> getCategories () {
return categories;
}
public void setCategories(ObservableList<Category> categories) {
this.categories = categories;
}
public ObservableList<Category> categoriesProperty () {
return categories;
}
}
package budget.model;
import java.time.LocalDate;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.RepeatFrequency;
import budget.util.LocalDateAdapter;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Category {
StringProperty name = new SimpleStringProperty("");
ObservableList<Category> children = FXCollections.observableArrayList();
StringProperty comments = new SimpleStringProperty("");
ObjectProperty<RepeatFrequency> repeatFrequency = new SimpleObjectProperty<RepeatFrequency>();
ObjectProperty<LocalDate> dueDate = new SimpleObjectProperty<LocalDate>();
DoubleProperty budgetAmount = new SimpleDoubleProperty();
DoubleProperty actualAmount = new SimpleDoubleProperty();
// name
public String getName() {
return name.getValue();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
// children
public ObservableList<Category> getChildren() {
return children;
}
public void setChildren(ObservableList<Category> children) {
this.children.setAll(children);
}
public void addChild(Category category) {
this.children.add(category);
}
// isParent
public Boolean isParent() {
// return this.parent.getValue();
if (children == null || children.isEmpty() || children.size() == 0) {
return false;
} else {
return true;
}
}
// comments
public String getComments() {
return comments.getValue();
}
public void setComments(String comments) {
this.comments.set(comments);
}
public StringProperty commentsProperty() {
return comments;
}
// repeatFrequency
public RepeatFrequency getRepeatFrequency() {
return this.repeatFrequency.getValue();
}
public void setRepeatFrequency(RepeatFrequency repeatFrequency) {
this.repeatFrequency.set(repeatFrequency);
}
public ObjectProperty<RepeatFrequency> repeatFrequencyProperty() {
return this.repeatFrequency;
}
// dueDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getDueDate() {
return this.dueDate.getValue();
}
public void setDueDate(LocalDate dueDate) {
this.dueDate.set(dueDate);
}
public ObjectProperty<LocalDate> dueDateProperty() {
return this.dueDate;
}
// budgetAmount
public Double getBudgetAmount() {
return this.budgetAmount.getValue();
}
public void setBudgetAmount(Double budgetAmount) {
this.budgetAmount.set(budgetAmount);
}
public DoubleProperty budgetAmountProperty() {
return this.budgetAmount;
}
// actualAmount
public Double getActualAmount() {
return this.actualAmount.getValue();
}
public void setActualAmount(Double actualAmount) {
this.actualAmount.set(actualAmount);
}
public DoubleProperty actualAmountProperty() {
return this.actualAmount;
}
}
There is another class that handles the marshalling. The function in this class is below
public void saveBudgetData(Budget budget) {
File file = new File(path + BUDGET_FILE);
try {
JAXBContext context = JAXBContext
.newInstance(Budget.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshalling and saving XML to the file.
m.marshal(budget, file);
} catch (Exception e) { // catches ANY exception
logger.error("exception: ", e);
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
I understand that this is a recursive relationship between categories. Is this what it is complaining about? I did not see find this scenario in my searching.
Thanks.
Cleaned up Budget and Category classes
package budget.model;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.DayOfWeek;
import budget.util.LocalDateAdapter;
#XmlRootElement(name = "budget")
public class BudgetNoFX {
// default to Sunday
DayOfWeek startOfWeek = DayOfWeek.SUNDAY;
// default to now
LocalDate startDate = LocalDate.now();
// number of days beyond week end to include in list of due bills
// default to 3
Integer daysBeyondWeek = new Integer(3);
Integer numberOfWeeks = new Integer(0);
ArrayList<CategoryNoFX> categories = new ArrayList<CategoryNoFX>();
// startOfWeek
public DayOfWeek getStartOfWeek() {
return this.startOfWeek;
}
public void setStartOfWeek(DayOfWeek startOfWeek) {
this.startOfWeek = startOfWeek;
}
// startDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getStartDate() {
return this.startDate;
}
public void setStartDate(LocalDate startDate){
this.startDate = startDate;
}
// daysBeyondWeek
public Integer getDaysBeyondWeek() {
return this.daysBeyondWeek;
}
public void setDaysBeyondWeek(Integer daysBeyondWeek) {
this.daysBeyondWeek = daysBeyondWeek;
}
// numberOFWeeks
public Integer getNumberOfWeeks() {
return this.numberOfWeeks;
}
public void setNumberOfWeeks(Integer numberOfWeeks) {
this.numberOfWeeks = numberOfWeeks;
}
// categories
public ArrayList<CategoryNoFX> getCategories () {
return categories;
}
public void setCategories(ArrayList<CategoryNoFX> categories) {
this.categories = categories;
}
}
package budget.model;
import java.time.LocalDate;
import java.util.ArrayList;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import budget.util.BudgetProperties.RepeatFrequency;
import budget.util.LocalDateAdapter;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class CategoryNoFX {
public static final String ROOT_CATEGORY = "ROOT";
String name = new String("");
ArrayList<CategoryNoFX> children = new ArrayList<CategoryNoFX>();
String comments = new String("");
// default to monthly
RepeatFrequency repeatFrequency = RepeatFrequency.MONTHLY;
LocalDate dueDate = LocalDate.now();
Double budgetAmount = new Double(0);
Double actualAmount = new Double(0);
// name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// children
public ArrayList<CategoryNoFX> getChildren() {
return children;
}
public void setChildren(ArrayList<CategoryNoFX> children) {
this.children = children;
}
public void addChild(CategoryNoFX category) {
this.children.add(category);
}
// isParent
public Boolean isParent() {
if (children == null || children.isEmpty() || children.size() == 0) {
return false;
} else {
return true;
}
}
// comments
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
// repeatFrequency
public RepeatFrequency getRepeatFrequency() {
return this.repeatFrequency;
}
public void setRepeatFrequency(RepeatFrequency repeatFrequency) {
this.repeatFrequency = repeatFrequency;
}
// dueDate
#XmlJavaTypeAdapter(LocalDateAdapter.class)
public LocalDate getDueDate() {
return this.dueDate;
}
public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}
// budgetAmount
public Double getBudgetAmount() {
return this.budgetAmount;
}
public void setBudgetAmount(Double budgetAmount) {
this.budgetAmount = budgetAmount;
}
// actualAmount
public Double getActualAmount() {
return this.actualAmount;
}
public void setActualAmount(Double actualAmount) {
this.actualAmount = actualAmount;
}
}
I updated the saveBudgetData function to use the new budget class
public void saveBudgetData(BudgetNoFX budget) {
File file = new File(path + BUDGET_FILE);
try {
JAXBContext context = JAXBContext
.newInstance(BudgetNoFX.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshalling and saving XML to the file.
m.marshal(budget, file);
} catch (Exception e) { // catches ANY exception
logger.error("exception: ", e);
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
I'm a bit embarrassed. I know you have to be careful with recursion and that was my problem.
Before building the ui, I hardcoded some values - created a budget and added some categories. I should have posted that code. I had set one of the categories as a child to itself.
Category food = new Category();
food.setName("Food");
categories.add(food);
Category groceries = new Category();
groceries.setBudgetAmount(new Double(120));
groceries.setName("Groceries");
// groceries.setParentCategory("Food");
groceries.setRepeatFrequency(RepeatFrequency.WEEKLY);
food.addChild(food); <-- problem line
Once I fixed the offending line to
food.addChild(groceries);
it started working.
I found it by by commenting out the save funciton to XML and instead wrote out my budget object to the screen.
I had recently read this tutorial: http://code.makery.ch/library/javafx-8-tutorial/ and built another simple app. This is where the LocalDateAdapter class came from. In part 5, he explains about jaxb and lists. I've made some code changes to better handle my lists and I'm getting xml output that I'm happy with.
Thanks for taking the time to look at my code and help me out.
If I ever get this done, maybe I'll post the app/code to the Internet. I've never done that before and don't know the best place though.
Again, thanks.
Chris
I am newbie to spring and java,
I have a case, where i am trying to fetching rows from the mysql table
This is my Controller:
#RequestMapping(value = "/pharmacy/order/dates", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public PharmacyOrderDateResponse orderDates(#Valid #RequestBody PharmacyOrderDateRequest request) {
List<PrescriptionOrder> pharmacyOrders = prescriptionOrderService.orderDatesByPharmacyId(request.getPharmacyId(), request.getOrderStatus(), true);
if(pharmacyOrders.size() == 0) {
throw new EntityNotFoundException("No pharmacy orders found");
}
PharmacyOrderDateResponse response = new PharmacyOrderDateResponse();
Set<Date> orderDateSet = new HashSet<>();
for(PrescriptionOrder pharmacyOrder : pharmacyOrders) {
//orderDateSet.add(longToDate(pharmacyOrder.getCreatedAt().getTime()));
}
response.setPharmacyId(pharmacyOrders.get(0).getPharmacyId());
response.setStatus(ResponseStatusCode.SUCCESS);
response.setPharmacyOrderDateDetails(orderDateSet);
response.setTotalDates(orderDateSet.size());
return response;
}
The above controller is used to call the service by the function, so that to get the list of prescription orders.
This is my Service:
package com.axonytes.corporate.service;
import java.util.Date;
import java.util.List;
import com.axonytes.corporate.entity.PrescriptionOrder;
public interface PrescriptionOrderService {
List<PrescriptionOrder> orderDatesByPharmacyId(Long labId, String orderStatus, Boolean status);
}
This is my ServiceImpl:
#Service
#Transactional(readOnly = true)
public class PrescriptionOrderServiceImpl implements PrescriptionOrderService {
private PrescriptionOrderRepository prescriptionOrderRepository;
#Autowired
public PrescriptionOrderServiceImpl(PrescriptionOrderRepository prescriptionOrderRepository) {
this.prescriptionOrderRepository = prescriptionOrderRepository;
}
#Override
public List<PrescriptionOrder> orderDatesByPharmacyId(Long pharmacyId, String orderStatus, Boolean status) {
OrderStatusEnum orderStatusEnum = OrderStatusEnum.fromString(orderStatus);
List<PrescriptionOrder> prescriptionOrder = prescriptionOrderRepository
.findByPharmacyIdAndOrderStatus(pharmacyId, orderStatusEnum.getStatus());
return prescriptionOrder;
}
}
The above service is a implementation function to list the orders, where it calls the repository function.
This is my Repository:
package com.axonytes.corporate.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.axonytes.corporate.entity.PrescriptionOrder;
#Repository
public interface PrescriptionOrderRepository extends JpaRepository<PrescriptionOrder, Long>{
//#Query(value = "select * from PrescriptionOrder po WHERE po.pharmacyId = :pharmacyId AND po.orderStatus = :orderStatus AND po.active = :active ORDER BY po.createdAt ASC")
//List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(#Param("pharmacyId") Long pharmacyId, #Param("orderStatus") int orderStatus, #Param("active") Boolean active);
List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(#Param("pharmacyId") Long pharmacyId, #Param("orderStatus") int orderStatus);
}
This is my Entity:
package com.axonytes.corporate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
#Entity
#DynamicInsert
#DynamicUpdate
#Table(name = "prescription_orders")
public class PrescriptionOrder extends BaseEntity {
private static final long serialVersionUID = -3853355500806579362L;
#Column(name = "prescription_id")
private Long prescriptionId;
#Column(name = "pharmacy_id")
private Long pharmacyId;
#Column(name = "order_status")
private int orderStatus;
public Long getPrescriptionId() {
return prescriptionId;
}
public void setPrescriptionId(Long prescriptionId) {
this.prescriptionId = prescriptionId;
}
public Long getPharmacyId() {
return pharmacyId;
}
public void setPharmacyId(Long pharmacyId) {
this.pharmacyId = pharmacyId;
}
public int getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(int orderStatus) {
this.orderStatus = orderStatus;
}
}
This ismy OrderStatusEnumClass:
package com.axonytes.corporate.util;
public enum OrderStatusEnum {
PENDING(0, "pending"), DESPATCHED(1, "dispatched");
private int status;
private String name;
OrderStatusEnum(int status, String name) {
this.status = status;
this.name = name;
}
public static OrderStatusEnum fromString(String name) {
if(name != null) {
for(OrderStatusEnum orderStatusEnum : OrderStatusEnum.values()) {
if(name.equalsIgnoreCase(orderStatusEnum.toString())) {
return orderStatusEnum;
}
}
}
return null;
}
#Override
public String toString() {
return name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
I have row values in the mysql:
id prescription_id pharmacy_id order_Status is_active
1 1 6 0 1
I am trying to list a orders by the following api.
http://localhost:8080/pharmacy/order/dates
POST METHOD with JSON VALUE:
{
"pharmacyId":"6",
"orderStatus":"pending"
}
Eventhough i am having 1 rows in the mysql db table, Output i am getting is:
{
"status": "FAILURE",
"errorCode": 0,
"errorMessage": "No pharmacy orders found"
}
Here you are using spring data and name method resolving. So is spring who translate the name of your method with each property in your entity, in that case you don't have to declare any parameter name so change your method to this:
#Repository
public interface PrescriptionOrderRepository extends JpaRepository<PrescriptionOrder, Long>{
List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(Long pharmacyId, int orderStatus);
}
Note: You have an enum OrderStatusEnum but you are saving into the database an integer, I highly recommend you to modify the object to store and change the int for the enum, would be easier to read
I am using the play-authenticate plugin in my play-framework project. I want to be able to use the user ID (of the user currently logged in) from the User.java model class of the plugin.
#Id
public Long id;
I want to do this so that when users are creating entries in a separate model class I can store the user who has created these entries. Is there functionality in place to access this information or would I need to write an additional method in the User class to return the active user?
package controllers;
import java.text.SimpleDateFormat;
import java.util.Date;
import models.*;
import models.User;
import play.Routes;
import play.data.Form;
import play.mvc.*;
import play.mvc.Http.Response;
import play.mvc.Http.Session;
import providers.MyUsernamePasswordAuthProvider;
import providers.MyUsernamePasswordAuthProvider.MyLogin;
import providers.MyUsernamePasswordAuthProvider.MySignup;
import play.data.*;
import views.html.*;
import play.*;
import be.objectify.deadbolt.actions.Restrict;
import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider;
public class Application extends Controller {
/*Part of the Play-Authenticate authentication plugin for the Play Framework.*/
public static final String FLASH_MESSAGE_KEY = "message";
public static final String FLASH_ERROR_KEY = "error";
public static final String USER_ROLE = "user";
public static User getLocalUser(final Session session) {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session));
return localUser;
}
/*Source: https://github.com/joscha/play-authenticate*/
#Restrict(Application.USER_ROLE)
public static Result restricted() {
final User localUser = getLocalUser(session());
return ok(journeyManagement.render(localUser));
}
/*Source: https://github.com/joscha/play-authenticate*/
#Restrict(Application.USER_ROLE)
public static Result profile() {
final User localUser = getLocalUser(session());
return ok(profile.render(localUser));
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result login() {
return ok(login.render(MyUsernamePasswordAuthProvider.LOGIN_FORM));
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result doLogin() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(login.render(filledForm));
} else {
// Everything was filled
return UsernamePasswordAuthProvider.handleLogin(ctx());
}
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result signup() {
return ok(signup.render(MyUsernamePasswordAuthProvider.SIGNUP_FORM));
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result jsRoutes() {
return ok(
Routes.javascriptRouter("jsRoutes",
controllers.routes.javascript.Signup.forgotPassword()))
.as("text/javascript");
}
/*Source: https://github.com/joscha/play-authenticate*/
public static Result doSignup() {
com.feth.play.module.pa.controllers.Authenticate.noCache(response());
final Form<MySignup> filledForm = MyUsernamePasswordAuthProvider.SIGNUP_FORM
.bindFromRequest();
if (filledForm.hasErrors()) {
// User did not fill everything properly
return badRequest(signup.render(filledForm));
} else {
// Everything was filled
// do something with your part of the form before handling the user
// signup
return UsernamePasswordAuthProvider.handleSignup(ctx());
}
}
/*Source: https://github.com/joscha/play-authenticate*/
public static String formatTimestamp(final long t) {
return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t));
}
}
Update:
package models;
import play.mvc.Http.Session;
import controllers.*;
import java.util.*;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import javax.persistence.*;
import play.data.format.*;
import com.avaje.ebean.*;
import java.text.*;
#Entity
public class Journey extends Model {
public SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm");
public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
#Id
public Long id;
#Required
public String start_loc;
#Required
public String end_loc;
#Required
public String participant_type;
#Required
public String date = simpleDateFormat.format(new Date());
#Required
public String time = simpleTimeFormat.format(new Date());
#ManyToOne
public User createUser;
#ManyToOne
public User modifyUser;
public static Finder<Long,Journey> find = new Finder(
Long.class, Journey.class
);
public static List<Journey> all() {
return find.all();
}
public static void create(Journey journey) {
journey.save();
}
public static void delete(Long id) {
find.ref(id).delete();
}
public static List<Journey> searchByAddress(String address) {
return find.where().ilike("start_loc", "%"+address+"%").findList();
}
public void save() {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
}
You don't need to write it manualy, for an example if you have a Book.java model you can add field for an example updatedBy to identify who was editing record last time, what's more you can override Model's methods save() and update(Object o) to make sure, that these fields will be always updated without additional effort.
#Entity
public class Book extends Model {
#Id
public Integer id;
#ManyToOne
public User createUser;
#ManyToOne
public User modifyUser;
public void save() {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
// other fields/methods
}