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

Legend:
Removed from v.580  
changed lines
  Added in v.1373

  ViewVC Help
Powered by ViewVC 1.1.20