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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 468 by torben, Thu Oct 22 06:04:45 2009 UTC revision 1158 by torben, Mon Oct 4 05:51:55 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3    import java.io.ByteArrayInputStream;
4    import java.io.ByteArrayOutputStream;
5    import java.io.File;
6  import java.io.IOException;  import java.io.IOException;
 import java.sql.Connection;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.List;  
7  import java.util.logging.Level;  import java.util.logging.Level;
8  import java.util.logging.Logger;  import java.util.logging.Logger;
9    
10  import javax.servlet.ServletException;  import javax.servlet.ServletException;
11    import javax.servlet.annotation.WebServlet;
12  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServlet;
13  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletRequest;
14  import javax.servlet.http.HttpServletResponse;  import javax.servlet.http.HttpServletResponse;
15  import javax.xml.parsers.DocumentBuilder;  
16  import javax.xml.parsers.DocumentBuilderFactory;  import javax.xml.transform.Source;
17  import javax.xml.transform.OutputKeys;  import javax.xml.transform.Templates;
18  import javax.xml.transform.Transformer;  import javax.xml.transform.Transformer;
19  import javax.xml.transform.TransformerFactory;  import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;  
20  import javax.xml.transform.stream.StreamResult;  import javax.xml.transform.stream.StreamResult;
21    import javax.xml.transform.stream.StreamSource;
22    
23  import org.w3c.dom.DOMImplementation;  import org.simpleframework.xml.Serializer;
24  import org.w3c.dom.Document;  import org.simpleframework.xml.core.Persister;
 import org.w3c.dom.Element;  
25    
26    import dk.thoerup.android.traininfo.common.DepartureBean;
27  import dk.thoerup.circuitbreaker.CircuitBreakerException;  import dk.thoerup.circuitbreaker.CircuitBreakerException;
28  import dk.thoerup.traininfoservice.DBConnection;  import dk.thoerup.traininfoservice.StationDAO;
29    import dk.thoerup.traininfoservice.Statistics;
30    
31  /**  /**
32   * Servlet implementation class DepartureServlet   * Servlet implementation class DepartureServlet
33   */   */
34    @WebServlet(urlPatterns={"/DepartureServlet"})
35  public class DepartureServlet extends HttpServlet {  public class DepartureServlet extends HttpServlet {
36          private static final long serialVersionUID = 1L;          private static final long serialVersionUID = 1L;
37                    
38          Logger logger = Logger.getLogger( DepartureServlet.class.getName() );          Logger logger = Logger.getLogger( DepartureServlet.class.getName() );
39    
40          DepartureFetcher fetcher = new DepartureFetcher();          DepartureFetcher fetcher;
41      TransformerFactory transformerFactory = TransformerFactory.newInstance();  
42          DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();  
43            
44            TransformerFactory xslTransFact;
45            Templates xslTemplate;
46                    
47    
48          @Override          @Override
49          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {          public void init() throws ServletException {
50                    super.init();
51    
52                    boolean useAzureSite =  Boolean.parseBoolean( getServletContext().getInitParameter("useazuresite") );
53                    int cacheTimeout =  Integer.parseInt( getServletContext().getInitParameter("cache_timeout") );
54                    int replyTimeout =  Integer.parseInt( getServletContext().getInitParameter("reply_timeout") );
55                    logger.info( "DepartureServlet, use azure site=" + useAzureSite + ", cache=" + cacheTimeout);
56                    fetcher = new DepartureFetcher(useAzureSite, cacheTimeout, replyTimeout);
57                    
58                    xslTransFact = TransformerFactory.newInstance();
59                    
60                    String xslPath = getServletContext().getRealPath("/departures.xsl");
61                    Source stylesheet = new StreamSource( new File(xslPath) );
62                    
63                    try {
64                            xslTemplate = xslTransFact.newTemplates(stylesheet);
65                    } catch (Exception e) {
66                            throw new ServletException(e);
67                    }
68            }
69    
70            @Override
71            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {          
72                  if (req.getParameter("station") == null) {                  if (req.getParameter("station") == null) {
73                          resp.sendError(400, "not enough parameters");                          resp.sendError(400, "not enough parameters");
74                          return;                          return;
75                  }                  }
76                                    
77                    boolean arrival = false;
78                    try {
79                            arrival = Integer.parseInt( req.getParameter("arrival")) != 0;
80                    } catch (Exception e) {}
81                    
82                    Statistics.getInstance().incrementDepartureLookups();
83                    
84                  int station = Integer.parseInt( req.getParameter("station") );                  int station = Integer.parseInt( req.getParameter("station") );
85                  String format = req.getParameter("format");                  String format = req.getParameter("format");
86    
87                  List<DepartureBean> beans;                  DepartureBean beans;            
   
                 String stationName = getStationName(station);  
88    
89                  try {                  try {
90                          beans = fetcher.cachedLookupDepartures(station);                          beans = fetcher.cachedLookupDepartures(station, arrival);
91                            beans.arrival = arrival;
92                  } catch (java.io.IOException ioe) {                  } catch (java.io.IOException ioe) {
93                          logger.warning("Read failed, station="+station + ". " + ioe.getMessage() );                          logger.warning("Read failed, station="+station + ". " + ioe.getMessage() );
94                            Statistics.getInstance().incrementDepartureErrors();
95                          resp.sendError(500);                          resp.sendError(500);
96                          return;                          return;
97                  } catch (CircuitBreakerException cbe) {                  } catch (CircuitBreakerException cbe) {
98                          logger.warning("Circuitbreaker - failing fast");                          logger.warning("Circuitbreaker - failing fast, station=" +station);
99                            Statistics.getInstance().incrementDepartureErrors();
100                          resp.sendError(500);                          resp.sendError(500);
101                          return;                          return;
102                    } catch (StationDAO.NostationException nse) {
103                            logger.log(Level.WARNING, "Station not in Database, station=" +station);
104                            Statistics.getInstance().incrementDepartureErrors();
105                            resp.sendError(400, "invalid station ID");
106                            return;                
107                  } catch (Exception e) {                                  } catch (Exception e) {                
108                          logger.log(Level.WARNING, "Unknown exception, station=" +station, e);                          logger.log(Level.WARNING, "Unknown exception, station=" +station, e);
109                            Statistics.getInstance().incrementDepartureErrors();
110                          resp.sendError(500);                          resp.sendError(500);
111                          return;                          return;
112                  }                  }
# Line 75  public class DepartureServlet extends Ht Line 116  public class DepartureServlet extends Ht
116                                    
117                  if (format.equalsIgnoreCase("xml")) {                  if (format.equalsIgnoreCase("xml")) {
118                          resp.setContentType("text/xml");                          resp.setContentType("text/xml");
119                          resp.getWriter().print( formatXml(beans, stationName) );                          resp.getWriter().print( formatXml(beans) );
120                  } else if (format.equalsIgnoreCase("html")) {                  } else if (format.equalsIgnoreCase("html")) {
121                          req.setAttribute("stationname", stationName );                          /*
122                            String advStr = req.getParameter("advanced");
123                            boolean advanced = advStr != null ? Boolean.parseBoolean(advStr) : false;
124                            
125                            req.setAttribute("advanced", advanced);
126                          req.setAttribute("departurebeans", beans);                          req.setAttribute("departurebeans", beans);
127                          req.setAttribute("stationID", station );                          req.setAttribute("stationID", station );
128                          getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);                          getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);*/
129                            resp.setContentType("text/html");
130                            resp.getWriter().print(  xmlToHtml(formatXml(beans))  );
131                  } else {                  } else {
132                          throw new ServletException("Unknown format");                          resp.sendError(400, "Unknown format");                  
133                  }                  }
134    
135          }          }
136    
137          protected String formatXml(List<DepartureBean> beans, String stationName) throws ServletException{          protected String formatXml(DepartureBean beans) throws ServletException{
138                  String xml = "";                  
139                  try {                  Serializer serializer = new Persister();
                         DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();  
                         DOMImplementation impl = builder.getDOMImplementation();  
   
                           
                         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);  
                           
                         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();  
140    
141                    ByteArrayOutputStream out = new ByteArrayOutputStream();
142    
143                    try {
144                            serializer.write(beans, out);
145                  } catch (Exception e) {                  } catch (Exception e) {
146                          throw new ServletException(e);                          throw new ServletException(e);
147                  }                  }
148                  return xml;                  
149                    return out.toString();
150          }          }
151            
152            protected String xmlToHtml(String input) throws ServletException {
153    
154          protected String getStationName(int stationID) {                  try {                                  
155                  String station = "";                          Transformer trans = xslTemplate.newTransformer();                      
156                    
157                  Connection conn = null;                          Source xml = new StreamSource( new ByteArrayInputStream(input.getBytes() ));
158                  try {                          ByteArrayOutputStream out = new ByteArrayOutputStream();
159                          conn = DBConnection.getConnection();                          trans.transform(xml, new StreamResult(out));            
160                          Statement stmt = conn.createStatement();                  
161                          ResultSet rs = stmt.executeQuery("SELECT name FROM trainstations WHERE id=" + stationID);                          return out.toString();
162                          if (rs.next()) {                  } catch (Exception e) {
163                                  station = rs.getString(1);                          throw new ServletException(e);
                         }  
   
                 } catch (Exception e) {  
                 } finally {  
                         try {  
                                 if (conn != null && !conn.isClosed())  
                                         conn.close();  
                         } catch (Exception e) {}  
164                  }                  }
   
                 return station;  
165          }          }
166    
167  }  }

Legend:
Removed from v.468  
changed lines
  Added in v.1158

  ViewVC Help
Powered by ViewVC 1.1.20