Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package b4f.servicios; import b4f.modelos.Punto; import b4f.modelos.TipoBici; import b4f.config.PersistenceManager; import b4f.modelos.Bici; import b4f.modelos.Multa; import b4f.modelos.Reserva; import b4f.modelos.Usuario; import b4f.seguridad.filtros.Requieres; import java.util.List; import javax.annotation.PostConstruct; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.ws.rs.Consumes; 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.core.MediaType; import javax.ws.rs.core.Response; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.subject.Subject; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author SamuelSalazar */ @Path("/puntos") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class PuntoService { @PersistenceContext private EntityManager entityManager; /** * Encargado de iniciar el entity manager despus de la creacin de una * nueva instancia */ @PostConstruct public void init() { try { entityManager = PersistenceManager.getInstance().getEntityManagerFactory().createEntityManager(); } catch (Exception e) { e.printStackTrace(); } } @GET public Response GET() throws Exception { Query q = entityManager.createQuery("select u from Punto u"); List<Punto> rta = q.getResultList(); return Response.status(200).entity(rta).build(); } @POST @Path("{idPunto}/bicis") @Requieres(roles = { "ADMINISTRADOR", "FUNCIONARIO" }) public Response registrarBici(@PathParam("idPunto") long idPunto, Bici bici) throws Exception { try { entityManager.getTransaction().begin(); Bici rta = entityManager.find(Bici.class, bici.getId()); Punto punto = entityManager.find(Punto.class, idPunto); if (rta == null) { throw new Exception("La bicicleta con id='" + bici.getId() + "' no existe"); } if (punto == null) { throw new Exception("El punto con id='" + idPunto + "' no existe"); } if (rta.getPunto() != null) { throw new Exception( "La bicicleta ya se encuentra registrada en el punto " + rta.getPunto().getNombre()); } punto.addBici(rta); rta.setPunto(punto); rta.setEstado(Bici.Estado.DISPONIBLE); entityManager.getTransaction().commit(); return Response.status(200).entity(rta).build(); } catch (Exception | Error e) { JSONObject err = new JSONObject(); err.put("error", e.getMessage()); return Response.status(400).entity(err).build(); } finally { entityManager.clear(); entityManager.close(); } } // Consultar el listado de bicis de un punto @GET @Path("{idPunto}/bicis") @Requieres(roles = { "ADMINISTRADOR", "FUNCIONARIO" }) public Response consultarBicis(@PathParam("idPunto") long idPunto) throws Exception { List bicis = null; Punto rta = entityManager.find(Punto.class, idPunto); if (rta != null) { bicis = rta.getBicis(); } JSONObject err = new JSONObject(); err.put("error", "el punto con id='" + idPunto + "' no existe"); return Response.status(bicis != null ? 200 : 404).entity(bicis != null ? bicis : err).build(); } @GET @Path("{id}") public Response getPunto(@PathParam("id") long id) { Punto rta = entityManager.find(Punto.class, id); JSONObject err = new JSONObject(); err.put("error", "el punto con id='" + id + "' no existe"); return Response.status(rta != null ? 200 : 404).entity(rta != null ? rta : err).build(); } @GET @Path("{id}/reservas") @Requieres(roles = { "ADMINISTRADOR", "FUNCIONARIO" }) public Response getReservas(@PathParam("id") long id) { Punto punto = entityManager.find(Punto.class, id); JSONObject err = new JSONObject(); err.put("error", "el punto con id='" + id + "' no existe"); Query q = entityManager.createQuery("Select r FROM Reserva r WHERE r.puntoPrestamo.id = :id") .setParameter("id", id); // .setParameter("estado", Reserva.Estado.RESERVADA); return Response.status(200).entity(q.getResultList()).build(); } @PUT @Path("{id}/reservas/{idReserva}") @Requieres(roles = { "FUNCIONARIO" }) public Response registrarPrestamo(@PathParam("id") long id_punto, @PathParam("idReserva") long id_reserva, JSONObject data) { try { entityManager.getTransaction().begin(); Punto punto = entityManager.find(Punto.class, id_punto); if (punto == null) { throw new Exception("el punto con id='" + id_punto + "' no existe"); } Reserva reserva = entityManager.find(Reserva.class, id_reserva); if (reserva == null) { throw new Exception("La reserva con id " + id_reserva + " no existe"); } final Subject subject = SecurityUtils.getSubject(); Object principal = subject.getPrincipal(); if (!(principal instanceof Usuario)) { throw new Exception("Usuario no autenticado"); } Usuario user = (Usuario) principal; if (!data.containsKey("accion")) { throw new Exception("Accion no especificada (PRESTAMO,RETORNO)"); } String accion = data.get("accion").toString(); if (!accion.equalsIgnoreCase("PRESTAMO") && !accion.equalsIgnoreCase("RETORNO")) { throw new Exception("Accion invalida (PRESTAMO, RETORNO)"); } if (accion.equalsIgnoreCase("PRESTAMO")) { //HACER EFECTIVA LA RESERVA if (reserva.getPuntoPrestamo().getId() != id_punto) { throw new Exception("El punto de prestamo no coincide con el de la reserva"); } if (reserva.getEstado() != Reserva.Estado.RESERVADA) { throw new Exception("La bicicleta no puede ser entregada."); } reserva.setPuntoPrestamo(punto); reserva.setEstado(Reserva.Estado.EN_PRESTAMO); reserva.getBici().setEstado(Bici.Estado.PRESTADA); reserva.getBici().setPunto(null); reserva.setFuncionarioEntrega(user); } else { // HACER EFECTIVA LA ENTREGA if (reserva.getEstado() != Reserva.Estado.EN_PRESTAMO) throw new Exception("La reserva no se encuentra en prestamo"); reserva.setEstado(Reserva.Estado.FINALIZADA); reserva.setPuntoRetorno(punto); reserva.getBici().setEstado(Bici.Estado.DISPONIBLE); reserva.getBici().setPunto(punto); punto.addBici(reserva.getBici()); reserva.setFuncionarioRecibo(user); reserva.setFecha_retorno(System.currentTimeMillis()); JSONArray arr = (JSONArray) data.get("multas"); Query q = entityManager.createQuery("Select m FROM Multa m WHERE m.id=:id"); if (arr != null) { for (int i = 0; i < arr.size(); i++) { long id_multa = Long.parseLong(arr.get(i).toString()); q.setParameter("id", id_multa); List res = q.getResultList(); if (res.isEmpty()) { throw new Exception("La multa con id " + id_multa + " no existe"); } Multa multa = (Multa) res.get(0); reserva.getMultas().add(multa); } } } entityManager.getTransaction().commit(); return Response.status(200).entity(reserva).build(); } catch (Exception e) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } JSONObject err = new JSONObject(); err.put("error", e.getMessage()); return Response.status(400).entity(err).build(); } finally { entityManager.clear(); entityManager.close(); } } @PUT @Path("{id}") @Requieres(roles = { "ADMINISTRADOR" }) public Response PUT(@PathParam("id") long id, Punto punto) { try { entityManager.getTransaction().begin(); Punto rta = entityManager.find(Punto.class, id); if (rta == null) { throw new Exception("el punto con id='" + id + "' no existe"); } rta.setNombre(punto.getNombre()); rta.setLatitud(punto.getLatitud()); rta.setLongitud(punto.getLongitud()); entityManager.getTransaction().commit(); return Response.status(200).entity(rta).build(); } catch (Exception | Error e) { JSONObject err = new JSONObject(); err.put("error", e.getMessage()); return Response.status(400).entity(err).build(); } finally { entityManager.clear(); entityManager.close(); } } @DELETE @Path("{id}") @Requieres(roles = { "ADMINISTRADOR" }) public Response deletePunto(@PathParam("id") long id) { JSONObject err = null, rta = null; try { entityManager.getTransaction().begin(); Punto tipo = entityManager.find(Punto.class, id); if (tipo == null) { throw new Exception("el punto con id='" + id + "' no existe"); } entityManager.remove(tipo); entityManager.getTransaction().commit(); rta = new JSONObject(); rta.put("mensaje", "el punto con id " + tipo.getId() + " fue eliminado correctamente"); } catch (Exception | Error e) { err = new JSONObject(); err.put("error", e.getMessage()); } finally { entityManager.clear(); entityManager.close(); } return Response.status(rta != null ? 200 : 400).entity(rta != null ? rta : err).build(); } @POST @Requieres(roles = { "ADMINISTRADOR" }) public Response POST(Punto tipo) { JSONObject rta = new JSONObject(); try { entityManager.getTransaction().begin(); tipo.validar(); entityManager.persist(tipo); entityManager.getTransaction().commit(); entityManager.refresh(tipo); rta.put("succes", true); } catch (Exception | Error t) { System.err.println("[ERROR] " + t.getMessage()); rta.put("error", t.getMessage()); if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } return Response.status(400).entity(rta).build(); } finally { entityManager.clear(); entityManager.close(); } return Response.status(201).entity(rta).build(); } }