package server.rest;
import java.net.URI;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import server.SpringAwareResource;
import server.model.Model;
import server.repo.ModelRepository;
@Path("/model")
@Produces(MediaType.APPLICATION_JSON)
public class ModelResource extends SpringAwareResource {
@Autowired
private ModelRepository repository;
// curl -i http://localhost:8080/model
@GET
public Iterable<Model> all() {
return repository.findAll();
}
// curl -i -X GET http://localhost:8080/model/<id>
@GET
@Path("{id: \\d+}")
public Response read(@PathParam("id") Long id) {
Model model = repository.findOne(id);
if (model == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.status(Response.Status.OK).entity(model).build();
}
// curl -i -X DELETE http://localhost:8080/model/<id>
@DELETE
@Path("{id: \\d+}")
public Response delete(@PathParam("id") Long id) {
repository.delete(id);
return Response.ok().build();
}
// curl -i -X PUT -H "Content-Type: application/json" -d '{"id":"<id>", "key": "k", "value": "v"}' http://localhost:8080/model
@PUT
public Response update(Model model) {
Model updated = repository.save(model);
return Response.created(URI.create("" + updated.id)).build();
}
// curl -i -X POST -H "Content-Type: application/json" -d '{"key": "k", "value": "v"}' http://localhost:8080/model
@POST
public Response create(Model model) {
if (model.id != 0) {
Response.status(Response.Status.BAD_REQUEST).entity("Invalid Id").build();
}
Model saved = repository.save(model);
return Response.created(URI.create("" + saved.id)).build();
}
}