package nl.utwente.mod4.pokemon.routes; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import nl.utwente.mod4.pokemon.dao.TrainerDao; import nl.utwente.mod4.pokemon.model.ResourceCollection; import nl.utwente.mod4.pokemon.model.Trainer; @Path("/trainers") public class TrainerRoute { @GET @Produces(MediaType.APPLICATION_JSON) public ResourceCollection<Trainer> getTrainers( @QueryParam("pageSize") int pageSize, @QueryParam("pageNumber") int pageNumber ) { // initializes page size and page number for request int ps = pageSize > 0 ? pageSize : Integer.MAX_VALUE; int pn = pageNumber > 0 ? pageNumber : 1; // request the desired page to the Data Access Object Trainer[] resources = TrainerDao.INSTANCE.getTrainers(ps, pn).toArray(new Trainer[0]); // updates the total and page size for the response int total = TrainerDao.INSTANCE.getTotalTrainers(); ps = resources == null ? 0 : resources.length; // returns a collection object containing the requested resources return new ResourceCollection<>(resources, ps, pn, total); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Trainer createTrainer(Trainer pokemonType) { // creates a resource based on to the JSON object sent by the client return TrainerDao.INSTANCE.create(pokemonType); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Trainer getTrainer(@PathParam("id") String id) { // returns to the client the resource with the desired id return TrainerDao.INSTANCE.getTrainer(id); } @PUT @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Trainer updateTrainer(@PathParam("id") String id, Trainer toReplace) { // check if the desired id and the id of the resource to be replaced match if (id == null || !id.equals(toReplace.id)) throw new BadRequestException("Id mismatch."); // return the object replaced return TrainerDao.INSTANCE.replace(toReplace); } @DELETE @Path("/{id}") public void deleteTrainer(@PathParam("id") String id) { // delete the resource with the desired id TrainerDao.INSTANCE.delete(id); } }