package dk.thoerup.traininfoservice.banedk; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; 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.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; 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; /** * 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 xslTransFact; Templates xslTemplate; @Override public void init() throws ServletException { super.init(); boolean useAzureSite = Boolean.parseBoolean( getServletContext().getInitParameter("useazuresite") ); int cacheTimeout = Integer.parseInt( getServletContext().getInitParameter("cache_timeout") ); 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"); 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"); 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, 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; } resp.setDateHeader("Expires", 0); resp.setHeader("Cache-Control", "no-cache, must-revalidate"); if (format.equalsIgnoreCase("xml")) { resp.setContentType("text/xml"); 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("departurebeans", beans); req.setAttribute("stationID", station ); getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);*/ resp.setContentType("text/html"); resp.getWriter().print( xmlToHtml(formatXml(beans)) ); } else { resp.sendError(400, "Unknown format"); } } protected String formatXml(DepartureBean beans) throws ServletException{ Serializer serializer = new Persister(); 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); } } }