/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java
ViewVC logotype

Contents of /android/TrainInfoService/src/dk/thoerup/traininfoservice/banedk/DepartureServlet.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 969 - (show annotations) (download)
Fri Jul 9 21:02:13 2010 UTC (13 years, 10 months ago) by torben
File size: 7099 byte(s)
include the arrival parameter in output xml
1 package dk.thoerup.traininfoservice.banedk;
2
3 import java.io.IOException;
4 import java.util.List;
5 import java.util.logging.Level;
6 import java.util.logging.Logger;
7
8 import javax.servlet.ServletException;
9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.xml.parsers.DocumentBuilder;
14 import javax.xml.parsers.DocumentBuilderFactory;
15 import javax.xml.transform.OutputKeys;
16 import javax.xml.transform.Transformer;
17 import javax.xml.transform.TransformerFactory;
18 import javax.xml.transform.dom.DOMSource;
19 import javax.xml.transform.stream.StreamResult;
20
21 import org.w3c.dom.DOMImplementation;
22 import org.w3c.dom.Document;
23 import org.w3c.dom.Element;
24
25 import dk.thoerup.circuitbreaker.CircuitBreakerException;
26 import dk.thoerup.traininfoservice.StationDAO;
27 import dk.thoerup.traininfoservice.Statistics;
28
29 /**
30 * Servlet implementation class DepartureServlet
31 */
32 @WebServlet(urlPatterns={"/DepartureServlet"})
33 public class DepartureServlet extends HttpServlet {
34 private static final long serialVersionUID = 1L;
35
36 Logger logger = Logger.getLogger( DepartureServlet.class.getName() );
37
38 DepartureFetcher fetcher;
39 TransformerFactory transformerFactory = TransformerFactory.newInstance();
40 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
41
42
43 @Override
44 public void init() throws ServletException {
45 super.init();
46
47 boolean useTempSite = Boolean.parseBoolean( getServletContext().getInitParameter("usetempsite") );
48 int cacheTimeout = Integer.parseInt( getServletContext().getInitParameter("cache_timeout") );
49 logger.info( "DepartureServlet, use temp site=" + useTempSite + ", cache=" + cacheTimeout);
50 fetcher = new DepartureFetcher(useTempSite, cacheTimeout);
51 }
52
53 @Override
54 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
55 if (req.getParameter("station") == null) {
56 resp.sendError(400, "not enough parameters");
57 return;
58 }
59
60 boolean arrival = false;
61 try {
62 arrival = Integer.parseInt( req.getParameter("arrival")) != 0;
63 } catch (Exception e) {}
64
65 Statistics.getInstance().incrementDepartureLookups();
66
67 int station = Integer.parseInt( req.getParameter("station") );
68 String format = req.getParameter("format");
69
70 List<DepartureBean> beans;
71
72 String stationName = StationDAO.getStationName(station);
73
74 try {
75 beans = fetcher.cachedLookupDepartures(station, arrival);
76 } catch (java.io.IOException ioe) {
77 logger.warning("Read failed, station="+station + ". " + ioe.getMessage() );
78 Statistics.getInstance().incrementDepartureErrors();
79 resp.sendError(500);
80 return;
81 } catch (CircuitBreakerException cbe) {
82 logger.warning("Circuitbreaker - failing fast");
83 Statistics.getInstance().incrementDepartureErrors();
84 resp.sendError(500);
85 return;
86 } catch (Exception e) {
87 logger.log(Level.WARNING, "Unknown exception, station=" +station, e);
88 Statistics.getInstance().incrementDepartureErrors();
89 resp.sendError(500);
90 return;
91 }
92
93 resp.setDateHeader("Expires", 0);
94 resp.setHeader("Cache-Control", "no-cache, must-revalidate");
95
96 if (format.equalsIgnoreCase("xml")) {
97 resp.setContentType("text/xml");
98 resp.getWriter().print( formatXml(beans, stationName, arrival) );
99 } else if (format.equalsIgnoreCase("html")) {
100
101 String advStr = req.getParameter("advanced");
102 boolean advanced = advStr != null ? Boolean.parseBoolean(advStr) : false;
103
104 req.setAttribute("advanced", advanced);
105 req.setAttribute("stationname", stationName );
106 req.setAttribute("departurebeans", beans);
107 req.setAttribute("stationID", station );
108 getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);
109 } else {
110 resp.sendError(400, "Unknown format");
111 }
112
113 }
114
115 protected String formatXml(List<DepartureBean> beans, String stationName, boolean arrival) throws ServletException{
116 String xml = "";
117 try {
118 DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
119 DOMImplementation impl = builder.getDOMImplementation();
120
121
122 Document doc = impl.createDocument(null,null,null);
123 Element root = doc.createElement("departureinfo");
124 root.setAttribute("station", stationName);
125 root.setAttribute("arrival", Boolean.toString(arrival) );
126 for (DepartureBean departure : beans) {
127 Element train = doc.createElement("train");
128
129 Element time = doc.createElement("time");
130 time.setTextContent( departure.getTime() );
131 train.appendChild(time);
132
133 Element updated = doc.createElement("updated");
134 updated.setTextContent( String.valueOf(departure.getUpdated()) );
135 train.appendChild(updated);
136
137 Element trainNumber = doc.createElement("trainnumber");
138 trainNumber.setTextContent( departure.getTrainNumber() );
139 train.appendChild(trainNumber);
140
141 Element destination = doc.createElement("destination");
142 destination.setTextContent( departure.getDestination());
143 train.appendChild(destination);
144
145 Element origin = doc.createElement("origin");
146 origin.setTextContent( departure.getOrigin() );
147 train.appendChild(origin);
148
149 Element location= doc.createElement("location");
150 location.setTextContent( departure.getLocation() );
151 train.appendChild(location);
152
153 Element status = doc.createElement("status");
154 status.setTextContent( departure.getStatus() );
155 train.appendChild(status);
156
157 Element note = doc.createElement("note");
158 note.setTextContent( departure.getNote() );
159 train.appendChild(note);
160
161 Element type = doc.createElement("type");
162 type.setTextContent( departure.getType() );
163 train.appendChild(type);
164
165 root.appendChild(train);
166 }
167
168 doc.appendChild(root);
169
170
171 DOMSource domSource = new DOMSource(doc);
172
173 Transformer transformer = transformerFactory.newTransformer();
174 //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
175 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
176 transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
177 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
178 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
179 java.io.StringWriter sw = new java.io.StringWriter();
180 StreamResult sr = new StreamResult(sw);
181 transformer.transform(domSource, sr);
182 xml = sw.toString();
183
184
185 } catch (Exception e) {
186 throw new ServletException(e);
187 }
188 return xml;
189 }
190
191 }

  ViewVC Help
Powered by ViewVC 1.1.20