package dk.thoerup.traininfoservice.banedk; import java.io.IOException; 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 org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; import dk.thoerup.android.traininfo.common.MetroBean; import dk.thoerup.circuitbreaker.CircuitBreakerException; @WebServlet(urlPatterns={"/MetroServlet"}) public class MetroServlet extends HttpServlet { private static final long serialVersionUID = 1L; Logger logger = Logger.getLogger(MetroServlet.class.getName()); MetroFetcher fetcher = new MetroFetcher(); protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("station") == null || req.getParameter("station").equals("") ) { resp.sendError(400, "not enough parameters"); return; } //TODO: How should statistics be handled for the metro //Statistics.getInstance().incrementDepartureLookups(); int station = Integer.parseInt( req.getParameter("station") ); MetroBean bean; try { bean = fetcher.cachedLookupMetroDepartures(station); String xml = formatXml(bean); resp.setDateHeader("Expires", 0); resp.setHeader("Cache-Control", "no-cache, must-revalidate"); resp.setContentType("text/xml"); resp.getWriter().print(xml); } catch (java.io.IOException ioe) { logger.warning("Metro read failed, station="+station + ". " + ioe.getMessage() ); //Statistics.getInstance().incrementDepartureErrors(); resp.sendError(500); return; } catch (CircuitBreakerException cbe) { logger.warning("Circuitbreaker - failing fast"); //Statistics.getInstance().incrementDepartureErrors(); resp.sendError(500); return; } catch (Exception e) { logger.log(Level.WARNING, "Unknown exception, metro-station=" +station, e); //Statistics.getInstance().incrementDepartureErrors(); resp.sendError(500); return; } } String formatXml(MetroBean metro) throws ServletException { Serializer serializer = new Persister(); StringWriter out = new StringWriter(); try { serializer.write(metro, out); } catch (Exception e) { throw new ServletException(e); } return out.toString(); } }