--- android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java 2010/06/10 22:26:09 829 +++ android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java 2010/10/18 11:49:01 1168 @@ -1,26 +1,29 @@ package dk.thoerup.traininfoservice.banedk; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; -import java.util.List; 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.Source; +import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; -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; @@ -28,32 +31,52 @@ /** * 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 { 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 { @@ -65,22 +88,26 @@ int station = Integer.parseInt( req.getParameter("station") ); String format = req.getParameter("format"); - List beans; - - String stationName = StationDAO.getStationName(station); + DepartureBean beans; try { beans = fetcher.cachedLookupDepartures(station, arrival); + 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(); @@ -93,96 +120,52 @@ 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); + 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(); + protected String formatXml(DepartureBean beans) throws ServletException{ + + Serializer serializer = new Persister(); - - 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(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + serializer.write(beans, out); + } catch (Exception e) { + throw new ServletException(e); + } + + return out.toString(); + } + + protected String xmlToHtml(String input) throws ServletException { + try { + Transformer trans = xslTemplate.newTransformer(); + + Source xml = new StreamSource( new ByteArrayInputStream(input.getBytes() )); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + trans.transform(xml, new StreamResult(out)); + + return out.toString(); } catch (Exception e) { throw new ServletException(e); } - return xml; } }