1 |
package dk.thoerup.traininfoservice.banedk; |
2 |
|
3 |
|
4 |
import java.io.IOException; |
5 |
import java.io.StringWriter; |
6 |
import java.util.logging.Level; |
7 |
import java.util.logging.Logger; |
8 |
|
9 |
import javax.servlet.ServletException; |
10 |
import javax.servlet.http.HttpServlet; |
11 |
import javax.servlet.http.HttpServletRequest; |
12 |
import javax.servlet.http.HttpServletResponse; |
13 |
|
14 |
import org.simpleframework.xml.Serializer; |
15 |
import org.simpleframework.xml.core.Persister; |
16 |
|
17 |
import dk.thoerup.android.traininfo.common.MetroBean; |
18 |
import dk.thoerup.circuitbreaker.CircuitBreakerException; |
19 |
import dk.thoerup.traininfoservice.Statistics; |
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
public class MetroServlet extends HttpServlet { |
26 |
|
27 |
private static final long serialVersionUID = 1L; |
28 |
|
29 |
Logger logger = Logger.getLogger(MetroServlet.class.getName()); |
30 |
|
31 |
MetroFetcher fetcher = new MetroFetcher(); |
32 |
|
33 |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { |
34 |
|
35 |
if (req.getParameter("station") == null) { |
36 |
resp.sendError(400, "not enough parameters"); |
37 |
return; |
38 |
} |
39 |
|
40 |
//TODO: How should statistics be handled for the metro |
41 |
//Statistics.getInstance().incrementDepartureLookups(); |
42 |
|
43 |
int station = Integer.parseInt( req.getParameter("station") ); |
44 |
|
45 |
|
46 |
MetroBean bean; |
47 |
|
48 |
try { |
49 |
|
50 |
bean = fetcher.cachedLookupMetroDepartures(station); |
51 |
String xml = formatXml(bean); |
52 |
|
53 |
resp.setDateHeader("Expires", 0); |
54 |
resp.setHeader("Cache-Control", "no-cache, must-revalidate"); |
55 |
resp.setContentType("text/xml"); |
56 |
resp.getWriter().print(xml); |
57 |
|
58 |
} catch (java.io.IOException ioe) { |
59 |
logger.warning("Metro read failed, station="+station + ". " + ioe.getMessage() ); |
60 |
//Statistics.getInstance().incrementDepartureErrors(); |
61 |
resp.sendError(500); |
62 |
return; |
63 |
} catch (CircuitBreakerException cbe) { |
64 |
logger.warning("Circuitbreaker - failing fast"); |
65 |
//Statistics.getInstance().incrementDepartureErrors(); |
66 |
resp.sendError(500); |
67 |
return; |
68 |
} catch (Exception e) { |
69 |
logger.log(Level.WARNING, "Unknown exception, metro-station=" +station, e); |
70 |
Statistics.getInstance().incrementDepartureErrors(); |
71 |
resp.sendError(500); |
72 |
return; |
73 |
} |
74 |
|
75 |
|
76 |
} |
77 |
|
78 |
String formatXml(MetroBean metro) throws ServletException { |
79 |
|
80 |
Serializer serializer = new Persister(); |
81 |
|
82 |
StringWriter out = new StringWriter(); |
83 |
|
84 |
try { |
85 |
serializer.write(metro, out); |
86 |
} catch (Exception e) { |
87 |
throw new ServletException(e); |
88 |
} |
89 |
|
90 |
return out.toString(); |
91 |
} |
92 |
|
93 |
} |