--- android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java 2009/10/21 08:43:45 462 +++ android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java 2011/04/28 10:13:36 1396 @@ -1,71 +1,116 @@ package dk.thoerup.traininfoservice.banedk; import java.io.IOException; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.List; +import java.io.StringWriter; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; +import javax.xml.transform.Templates; import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; +import org.simpleframework.xml.Serializer; +import org.simpleframework.xml.core.Persister; -import dk.thoerup.curcuitbreaker.CircuitBreakerException; -import dk.thoerup.traininfoservice.DBConnection; +import dk.thoerup.android.traininfo.common.DepartureBean; +import dk.thoerup.android.traininfo.common.StationBean; +import dk.thoerup.circuitbreaker.CircuitBreakerException; +import dk.thoerup.traininfoservice.Statistics; +import dk.thoerup.traininfoservice.TraininfoSettings; +import dk.thoerup.traininfoservice.banedk.DepartureFetcher.FetchTrainType; +import dk.thoerup.traininfoservice.db.StationDAO; /** * Servlet implementation class DepartureServlet */ +@WebServlet(urlPatterns={"/DepartureServlet"}) public class DepartureServlet extends HttpServlet { private static final long serialVersionUID = 1L; Logger logger = Logger.getLogger( DepartureServlet.class.getName() ); - DepartureFetcher fetcher = new DepartureFetcher(); - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + DepartureFetcher fetcher; + + + + TransformerFactory xslTransFact; + Templates xslTemplate; @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + public void init() throws ServletException { + super.init(); + + + TraininfoSettings settings = (TraininfoSettings) getServletContext().getAttribute("settings"); + fetcher = new DepartureFetcher(settings); + + /* + xslTransFact = TransformerFactory.newInstance(); + + String xslPath = getServletContext().getRealPath("/departures.xsl"); + Source stylesheet = new StreamSource( new File(xslPath) ); + + try { + xslTemplate = xslTransFact.newTemplates(stylesheet); + } catch (Exception e) { + throw new ServletException(e); + }*/ + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("station") == null) { - resp.sendError(400, "not enough parameters"); + resp.sendError(400, "not enough parameters (station)"); return; } + if (req.getParameter("format") == null) { + resp.sendError(400, "not enough parameters (format)"); + return; + } + + boolean arrival = false; + try { + arrival = Integer.parseInt( req.getParameter("arrival")) != 0; + } catch (Exception e) {} + + Statistics.getInstance().incrementDepartureLookups(); int station = Integer.parseInt( req.getParameter("station") ); String format = req.getParameter("format"); - List beans; - - String stationName = getStationName(station); + DepartureBean beans; + + DepartureFetcher.FetchTrainType type = FetchTrainType.BOTH; + if ( req.getParameter("type") != null) { + type = FetchTrainType.valueOf( req.getParameter("type") ); + } + try { - beans = fetcher.cachedLookupDepartures(station); + beans = fetcher.cachedLookupDepartures(station, arrival, type); + beans.arrival = arrival; } catch (java.io.IOException ioe) { logger.warning("Read failed, station="+station + ". " + ioe.getMessage() ); - resp.sendError(500); + Statistics.getInstance().incrementDepartureErrors(); + resp.sendError(500, "backend didnt answer"); return; } catch (CircuitBreakerException cbe) { - logger.warning("Circuitbreaker - failing fast"); - resp.sendError(500); - return; + logger.warning("Circuitbreaker - failing fast, station=" +station); + Statistics.getInstance().incrementDepartureErrors(); + beans = generateErrorBean(1); + } catch (StationDAO.NostationException nse) { + logger.log(Level.WARNING, "Station not in Database, station=" +station); + Statistics.getInstance().incrementDepartureErrors(); + resp.sendError(400, "invalid station ID"); + return; } catch (Exception e) { logger.log(Level.WARNING, "Unknown exception, station=" +station, e); + Statistics.getInstance().incrementDepartureErrors(); resp.sendError(500); return; } @@ -75,110 +120,59 @@ if (format.equalsIgnoreCase("xml")) { resp.setContentType("text/xml"); - resp.getWriter().print( formatXml(beans, stationName) ); + resp.getWriter().print( formatXml(beans) ); } else if (format.equalsIgnoreCase("html")) { - req.setAttribute("stationname", stationName ); + + String advStr = req.getParameter("advanced"); + boolean advanced = advStr != null ? Boolean.parseBoolean(advStr) : false; + + req.setAttribute("advanced", advanced); req.setAttribute("departurebeans", beans); req.setAttribute("stationID", station ); getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp); + /*resp.setContentType("text/html"); + resp.getWriter().print( xmlToHtml(formatXml(beans)) );*/ } else { - throw new ServletException("Unknown format"); + resp.sendError(400, "Unknown format"); } - + } + + protected DepartureBean generateErrorBean(int code) { + DepartureBean bean = new DepartureBean(); + bean.stationName=""; + bean.errorCode = code; + return bean; } - protected String formatXml(List beans, String stationName) throws ServletException{ - String xml = ""; - try { - DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); - DOMImplementation impl = builder.getDOMImplementation(); - - - Document doc = impl.createDocument(null,null,null); - Element root = doc.createElement("departureinfo"); - root.setAttribute("station", stationName); - for (DepartureBean departure : beans) { - Element train = doc.createElement("train"); - - Element time = doc.createElement("time"); - time.setTextContent( departure.getTime() ); - train.appendChild(time); - - Element updated = doc.createElement("updated"); - updated.setTextContent( String.valueOf(departure.getUpdated()) ); - train.appendChild(updated); - - Element trainNumber = doc.createElement("trainnumber"); - trainNumber.setTextContent( departure.getTrainNumber() ); - train.appendChild(trainNumber); - - Element destination = doc.createElement("destination"); - destination.setTextContent( departure.getDestination()); - train.appendChild(destination); - - Element origin = doc.createElement("origin"); - origin.setTextContent( departure.getOrigin() ); - train.appendChild(origin); - - Element location= doc.createElement("location"); - location.setTextContent( departure.getLocation() ); - train.appendChild(location); - - Element status = doc.createElement("status"); - status.setTextContent( departure.getStatus() ); - train.appendChild(status); - - Element note = doc.createElement("note"); - note.setTextContent( departure.getNote() ); - train.appendChild(note); - - root.appendChild(train); - } - - doc.appendChild(root); - - - DOMSource domSource = new DOMSource(doc); - - Transformer transformer = transformerFactory.newTransformer(); - //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - java.io.StringWriter sw = new java.io.StringWriter(); - StreamResult sr = new StreamResult(sw); - transformer.transform(domSource, sr); - xml = sw.toString(); + protected String formatXml(DepartureBean beans) throws ServletException{ + + Serializer serializer = new Persister(); + StringWriter out = new StringWriter(); + try { + serializer.write(beans, out); } catch (Exception e) { throw new ServletException(e); } - return xml; + + return out.toString(); } + /* + protected String xmlToHtml(String input) throws ServletException { - protected String getStationName(int stationID) { - String station = ""; - - Connection conn = null; - try { - conn = DBConnection.getConnection(); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT name FROM trainstations WHERE id=" + stationID); - if (rs.next()) { - station = rs.getString(1); - } - - } catch (Exception e) { - } finally { - try { - if (conn != null && !conn.isClosed()) - conn.close(); - } catch (Exception e) {} + try { + Transformer trans = xslTemplate.newTransformer(); + + + Source xml = new StreamSource( new StringReader(input)); + StringWriter out = new StringWriter(); + trans.transform(xml, new StreamResult(out)); + + return out.toString(); + } catch (Exception e) { + throw new ServletException(e); } - - return station; - } + }*/ }