/[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 421 by torben, Thu Oct 8 12:19:42 2009 UTC revision 969 by torben, Fri Jul 9 21:02:13 2010 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;
 import java.sql.Connection;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
4  import java.util.List;  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;
# Line 24  import org.w3c.dom.DOMImplementation; Line 22  import org.w3c.dom.DOMImplementation;
22  import org.w3c.dom.Document;  import org.w3c.dom.Document;
23  import org.w3c.dom.Element;  import org.w3c.dom.Element;
24    
25  import dk.thoerup.curcuitbreaker.CircuitBreakerException;  import dk.thoerup.circuitbreaker.CircuitBreakerException;
26  import dk.thoerup.traininfoservice.DBConnection;  import dk.thoerup.traininfoservice.StationDAO;
27    import dk.thoerup.traininfoservice.Statistics;
28    
29  /**  /**
30   * Servlet implementation class DepartureServlet   * Servlet implementation class DepartureServlet
31   */   */
32    @WebServlet(urlPatterns={"/DepartureServlet"})
33  public class DepartureServlet extends HttpServlet {  public class DepartureServlet extends HttpServlet {
34          private static final long serialVersionUID = 1L;          private static final long serialVersionUID = 1L;
35                    
36          Logger logger = Logger.getLogger( DepartureServlet.class.getName() );          Logger logger = Logger.getLogger( DepartureServlet.class.getName() );
37    
38          DepartureFetcher fetcher = new DepartureFetcher();          DepartureFetcher fetcher;
39      TransformerFactory transformerFactory = TransformerFactory.newInstance();      TransformerFactory transformerFactory = TransformerFactory.newInstance();
40          DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();          DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
41                    
42    
43          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {          @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") );                  int station = Integer.parseInt( req.getParameter("station") );
68                  String format = req.getParameter("format");                  String format = req.getParameter("format");
69    
70                  List<DepartureBean> beans;                  List<DepartureBean> beans;
71    
72                  String stationName = getStationName(station);                  String stationName = StationDAO.getStationName(station);
73    
74                  try {                  try {
75                          beans = fetcher.cachedLookupDepartures(station);                          beans = fetcher.cachedLookupDepartures(station, arrival);
76                  } catch (java.net.SocketTimeoutException ste) {                  } catch (java.io.IOException ioe) {
77                          logger.warning("Read timed out, station="+station);                          logger.warning("Read failed, station="+station + ". " + ioe.getMessage() );
78                            Statistics.getInstance().incrementDepartureErrors();
79                          resp.sendError(500);                          resp.sendError(500);
80                          return;                          return;
81                  } catch (CircuitBreakerException cbe) {                  } catch (CircuitBreakerException cbe) {
82                          logger.warning("Circuitbreaker - failing fast");                          logger.warning("Circuitbreaker - failing fast");
83                            Statistics.getInstance().incrementDepartureErrors();
84                          resp.sendError(500);                          resp.sendError(500);
85                          return;                          return;
86                  } catch (Throwable e) {                                  } catch (Exception e) {                
87                          logger.log(Level.WARNING, "Unknown exception, station=" +station, e);                          logger.log(Level.WARNING, "Unknown exception, station=" +station, e);
88                            Statistics.getInstance().incrementDepartureErrors();
89                          resp.sendError(500);                          resp.sendError(500);
90                          return;                          return;
91                  }                  }
# Line 69  public class DepartureServlet extends Ht Line 95  public class DepartureServlet extends Ht
95                                    
96                  if (format.equalsIgnoreCase("xml")) {                  if (format.equalsIgnoreCase("xml")) {
97                          resp.setContentType("text/xml");                          resp.setContentType("text/xml");
98                          resp.getWriter().print( formatXml(beans, stationName) );                          resp.getWriter().print( formatXml(beans, stationName, arrival) );
99                  } else if (format.equalsIgnoreCase("html")) {                  } 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 );                          req.setAttribute("stationname", stationName );
106                          req.setAttribute("departurebeans", beans);                          req.setAttribute("departurebeans", beans);
107                          req.setAttribute("stationID", station );                          req.setAttribute("stationID", station );
108                          getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);                          getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);
109                  } else {                  } else {
110                          throw new ServletException("Unknown format");                          resp.sendError(400, "Unknown format");                  
111                  }                  }
112    
113          }          }
114    
115          protected String formatXml(List<DepartureBean> beans, String stationName) throws ServletException{          protected String formatXml(List<DepartureBean> beans, String stationName, boolean arrival) throws ServletException{
116                  String xml = "";                  String xml = "";
117                  try {                  try {
118                          DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();                          DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
# Line 91  public class DepartureServlet extends Ht Line 122  public class DepartureServlet extends Ht
122                          Document doc = impl.createDocument(null,null,null);                          Document doc = impl.createDocument(null,null,null);
123                  Element root = doc.createElement("departureinfo");                  Element root = doc.createElement("departureinfo");
124                  root.setAttribute("station", stationName);                  root.setAttribute("station", stationName);
125                    root.setAttribute("arrival", Boolean.toString(arrival) );
126                  for (DepartureBean departure : beans) {                  for (DepartureBean departure : beans) {
127                          Element train = doc.createElement("train");                          Element train = doc.createElement("train");
128                                                    
# Line 126  public class DepartureServlet extends Ht Line 158  public class DepartureServlet extends Ht
158                          note.setTextContent( departure.getNote() );                          note.setTextContent( departure.getNote() );
159                          train.appendChild(note);                          train.appendChild(note);
160                                                    
161                            Element type = doc.createElement("type");
162                            type.setTextContent( departure.getType() );
163                            train.appendChild(type);
164                            
165                          root.appendChild(train);                          root.appendChild(train);
166                  }                  }
167                                    
# Line 138  public class DepartureServlet extends Ht Line 174  public class DepartureServlet extends Ht
174                  //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");                  //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
175                  transformer.setOutputProperty(OutputKeys.METHOD, "xml");                  transformer.setOutputProperty(OutputKeys.METHOD, "xml");
176                  transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");                  transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
177                  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");                  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
178                  transformer.setOutputProperty(OutputKeys.INDENT, "yes");                  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
179                  java.io.StringWriter sw = new java.io.StringWriter();                  java.io.StringWriter sw = new java.io.StringWriter();
180                  StreamResult sr = new StreamResult(sw);                  StreamResult sr = new StreamResult(sw);
# Line 152  public class DepartureServlet extends Ht Line 188  public class DepartureServlet extends Ht
188                  return xml;                  return xml;
189          }          }
190    
         protected String getStationName(int stationID) {  
                 String station = "";  
   
                 Connection conn = null;  
                 try {  
                         conn = DBConnection.getConnection();  
                         Statement stmt = conn.createStatement();  
                         ResultSet rs = stmt.executeQuery("SELECT name FROM trainstations WHERE id=" + stationID);  
                         if (rs.next()) {  
                                 station = rs.getString(1);  
                         }  
   
                 } catch (Exception e) {  
                 } finally {  
                         try {  
                                 if (conn != null && !conn.isClosed())  
                                         conn.close();  
                         } catch (Exception e) {}  
                 }  
   
                 return station;  
         }  
   
191  }  }

Legend:
Removed from v.421  
changed lines
  Added in v.969

  ViewVC Help
Powered by ViewVC 1.1.20