--- android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java 2010/05/03 07:42:02 697 +++ android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java 2011/04/04 08:59:46 1253 @@ -1,78 +1,116 @@ package dk.thoerup.traininfoservice.banedk; import java.io.IOException; -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.android.traininfo.common.DepartureBean; import dk.thoerup.circuitbreaker.CircuitBreakerException; import dk.thoerup.traininfoservice.StationDAO; +import dk.thoerup.traininfoservice.Statistics; +import dk.thoerup.traininfoservice.banedk.DepartureFetcher.FetchTrainType; /** * 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; - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + + + + TransformerFactory xslTransFact; + Templates xslTemplate; @Override public void init() throws ServletException { super.init(); - boolean useTempSite = Boolean.parseBoolean( getServletContext().getInitParameter("usetempsite") ); + boolean useAzureSite = Boolean.parseBoolean( getServletContext().getInitParameter("useazuresite") ); int cacheTimeout = Integer.parseInt( getServletContext().getInitParameter("cache_timeout") ); - logger.info( "DepartureServlet, use temp site=" + useTempSite + ", cache=" + cacheTimeout); - fetcher = new DepartureFetcher(useTempSite, cacheTimeout); + int replyTimeout = Integer.parseInt( getServletContext().getInitParameter("reply_timeout") ); + logger.info( "DepartureServlet, use azure site=" + useAzureSite + ", cache=" + cacheTimeout); + fetcher = new DepartureFetcher(useAzureSite, cacheTimeout, replyTimeout); + + /* + 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 { + 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 = StationDAO.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() ); + Statistics.getInstance().incrementDepartureErrors(); resp.sendError(500); return; } catch (CircuitBreakerException cbe) { - logger.warning("Circuitbreaker - failing fast"); + logger.warning("Circuitbreaker - failing fast, station=" +station); + Statistics.getInstance().incrementDepartureErrors(); resp.sendError(500); return; + } 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; } @@ -82,96 +120,53 @@ if (format.equalsIgnoreCase("xml")) { resp.setContentType("text/xml"); - resp.getWriter().print( formatXml(beans, stationName) ); + resp.getWriter().print( formatXml(beans) ); } else if (format.equalsIgnoreCase("html")) { String advStr = req.getParameter("advanced"); boolean advanced = advStr != null ? Boolean.parseBoolean(advStr) : false; req.setAttribute("advanced", advanced); - req.setAttribute("stationname", stationName ); 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 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); - - Element type = doc.createElement("type"); - type.setTextContent( departure.getType() ); - train.appendChild(type); - - 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 { + + 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); + } + }*/ }