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 rest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import deploy.DeploymentConfiguration; import entity.FlightInstance; import exception.FlightException; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import us.monoid.json.JSONException; /** * * @author Andreas Styltsvig */ @Path("flightreservation") public class FlightReservation { private static EntityManagerFactory emf = Persistence .createEntityManagerFactory(DeploymentConfiguration.PU_NAME); private static EntityManager em = emf.createEntityManager(); private static Gson gson = new GsonBuilder().setPrettyPrinting().create(); @POST @Produces(MediaType.APPLICATION_JSON) public Response reservation(String jsonReservation) throws IOException, JSONException, FlightException { JsonObject jsonObj = new JsonParser().parse(jsonReservation).getAsJsonObject(); FlightInstance flight = em.find(FlightInstance.class, jsonObj.get("flightID").getAsString()); int numberOfSeats = 0; try { numberOfSeats = Integer.parseInt(jsonObj.get("numberOfSeats").getAsString()); } catch (Exception e) { } if (flight.getAvailableSeats() > numberOfSeats) { flight.setAvailableSeats(flight.getAvailableSeats() - numberOfSeats); em.getTransaction().begin(); em.merge(flight); em.getTransaction().commit(); jsonObj.remove("ReservePhone"); jsonObj.remove("ReserveeEmail"); jsonObj.addProperty("Origin", flight.getOrigin().getCity() + " (" + flight.getOrigin().getIatacode() + ")"); jsonObj.addProperty("Destination", flight.getDestination().getCity() + " (" + flight.getDestination().getIatacode() + ")"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Date date = flight.getDepartureDate(); Date time = flight.getDepartureTime(); date.setHours(time.getHours()); date.setMinutes(time.getMinutes()); String newDate = df.format(date); jsonObj.addProperty("Date", newDate); jsonObj.addProperty("FlightTime", flight.getTravelTime()); } else throw new FlightException("Not enough available seats"); return Response.accepted(gson.toJson(jsonObj)).build(); } }