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 cimitero.rest; import cimitero.dto.ItemWrapper; import cimitero.dto.ResponseDto; import cimitero.entities.TCoordinate; import cimitero.persistence.HibernateUtil; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.hibernate.Session; import org.jboss.logging.Logger; /** * REST Web Service * * @author Markus */ @Stateless @Path("/coordinate") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public class CoordinateRESTService { Logger log = Logger.getLogger(InitRESTService.class); public CoordinateRESTService() { } // get all coordinate entries @GET public ResponseDto getAllCoordinates() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<TCoordinate> results = session.createCriteria(TCoordinate.class).list(); ResponseDto response = new ResponseDto(true); if (results.isEmpty()) { response.setOk(false); response.addError(1, "no entries found"); } else { response.setItems(new ItemWrapper<TCoordinate>(results)); } session.getTransaction().commit(); return response; } // get coordinate by id @GET @Path("{id}") public ResponseDto getCoordinateById(@PathParam("id") Integer id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); TCoordinate result = (TCoordinate) session.get(TCoordinate.class, id); ResponseDto response = new ResponseDto(true); if (result == null) { response.setOk(false); response.addError(1, "coordinate with id " + id + " not found"); } else { List<TCoordinate> results = new ArrayList<TCoordinate>(); results.add(result); response.setItems(new ItemWrapper(results)); } session.getTransaction().commit(); return response; } // save or update coordinate @POST public ResponseDto updateCoordinate(TCoordinate coordinate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); if (coordinate.getCoordinateId() == -1) coordinate.setCoordinateId(null); session.saveOrUpdate(coordinate); ResponseDto response = new ResponseDto(true); session.getTransaction().commit(); return response; } // delete coordinate @DELETE @Path("{id}") public ResponseDto removeCoordinate(@PathParam("id") Integer id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); TCoordinate result = (TCoordinate) session.get(TCoordinate.class, id); session.delete(result); ResponseDto response = new ResponseDto(true); session.getTransaction().commit(); return response; } }