Skip to content
Snippets Groups Projects

Issue #18, #19 resolved

1 file
+ 18
9
Compare changes
  • Side-by-side
  • Inline
package nl.utwente.mod4.pokemon.routes;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.*;
import nl.utwente.mod4.pokemon.dao.PokemonDao;
import nl.utwente.mod4.pokemon.model.Pokemon;
import nl.utwente.mod4.pokemon.model.ResourceCollection;
@Path("/pokemon")
public class PokemonRoute {
@GET
@Produces(MediaType.APPLICATION_JSON)
public ResourceCollection<Pokemon> getPokemon(
@QueryParam("sortBy") String sortOrder,
@QueryParam("pageSize") int pageSize,
@QueryParam("pageNumber") int pageNum
) {
Integer ps = pageSize > 0 ? pageSize : Integer.MAX_VALUE;
Integer pn = pageNum > 0 ? pageNum : 1;
Pokemon [] pokemons = PokemonDao.INSTANCE.getPokemon(ps, pn).toArray(new Pokemon[0]);
if (sortOrder != null && sortOrder.equals("name")) {
pokemons = Arrays.stream(pokemons).sorted(Comparator.comparing(p -> p.name)).toArray(Pokemon[]::new);
// pokemons.sort(Comparator.comparing(pok -> pok.name));
}
Integer totalPokemons = PokemonDao.INSTANCE.getTotalPokemon();
ps = pokemons == null ? 0 : pokemons.length;
return new ResourceCollection<>(pokemons, ps, pn, totalPokemons);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Pokemon createNewPokemon(Pokemon pokemon) {
if (pokemon.created != null || pokemon.id != null || pokemon.lastUpDate !=null) {
throw new BadRequestException();
}
return PokemonDao.INSTANCE.create(pokemon);
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Pokemon getPokemonById(@PathParam("id") String id) {
Pokemon gotPokemon;
try {
gotPokemon = PokemonDao.INSTANCE.getPokemon(id);
} catch (NotFoundException e) {
throw new WebApplicationException(404);
}
return gotPokemon;
}
@DELETE
@Path("/{id}")
public Response deletePokemonById(@PathParam("id") String id) {
PokemonDao.INSTANCE.delete(id);
return Response.noContent().build();
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Pokemon updatePokemon(@PathParam("id") String id, Pokemon updatedPokemon) {
if (id == null || !id.equals(updatedPokemon.id))
throw new BadRequestException("Id mismatch.");
return PokemonDao.INSTANCE.replace(updatedPokemon);
}
}
Loading