/[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 1026 by torben, Thu Sep 2 18:37:49 2010 UTC revision 1253 by torben, Mon Apr 4 08:59:46 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.io.StringWriter;
5  import java.util.logging.Level;  import java.util.logging.Level;
6  import java.util.logging.Logger;  import java.util.logging.Logger;
7    
# Line 9  import javax.servlet.annotation.WebServl Line 10  import javax.servlet.annotation.WebServl
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.circuitbreaker.CircuitBreakerException;  import dk.thoerup.circuitbreaker.CircuitBreakerException;
21    import dk.thoerup.traininfoservice.StationDAO;
22  import dk.thoerup.traininfoservice.Statistics;  import dk.thoerup.traininfoservice.Statistics;
23    import dk.thoerup.traininfoservice.banedk.DepartureFetcher.FetchTrainType;
24    
25  /**  /**
26   * Servlet implementation class DepartureServlet   * Servlet implementation class DepartureServlet
# Line 34  public class DepartureServlet extends Ht Line 32  public class DepartureServlet extends Ht
32          Logger logger = Logger.getLogger( DepartureServlet.class.getName() );          Logger logger = Logger.getLogger( DepartureServlet.class.getName() );
33    
34          DepartureFetcher fetcher;          DepartureFetcher fetcher;
35      TransformerFactory transformerFactory = TransformerFactory.newInstance();  
36          DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();  
37            
38            TransformerFactory xslTransFact;
39            Templates xslTemplate;
40                    
41    
42          @Override          @Override
43          public void init() throws ServletException {          public void init() throws ServletException {
44                  super.init();                  super.init();
45    
46                  boolean useTempSite =  Boolean.parseBoolean( getServletContext().getInitParameter("usetempsite") );                  boolean useAzureSite =  Boolean.parseBoolean( getServletContext().getInitParameter("useazuresite") );
47                  int cacheTimeout =  Integer.parseInt( getServletContext().getInitParameter("cache_timeout") );                  int cacheTimeout =  Integer.parseInt( getServletContext().getInitParameter("cache_timeout") );
48                  int replyTimeout =  Integer.parseInt( getServletContext().getInitParameter("reply_timeout") );                  int replyTimeout =  Integer.parseInt( getServletContext().getInitParameter("reply_timeout") );
49                  logger.info( "DepartureServlet, use temp site=" + useTempSite + ", cache=" + cacheTimeout);                  logger.info( "DepartureServlet, use azure site=" + useAzureSite + ", cache=" + cacheTimeout);
50                  fetcher = new DepartureFetcher(useTempSite, cacheTimeout, replyTimeout);                  fetcher = new DepartureFetcher(useAzureSite, cacheTimeout, replyTimeout);
51                    
52                    /*
53                    xslTransFact = TransformerFactory.newInstance();
54                    
55                    String xslPath = getServletContext().getRealPath("/departures.xsl");
56                    Source stylesheet = new StreamSource( new File(xslPath) );
57                    
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;                  boolean arrival = false;
77                  try {                  try {
# Line 66  public class DepartureServlet extends Ht Line 83  public class DepartureServlet extends Ht
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                  DepartureBean beans;                              DepartureBean beans;
87                    
88                    DepartureFetcher.FetchTrainType type = FetchTrainType.BOTH;
89                    if ( req.getParameter("type") != null) {
90                            type = FetchTrainType.valueOf( req.getParameter("type") );
91                    }
92    
93                  try {                  try {
94                          beans = fetcher.cachedLookupDepartures(station, arrival);                          beans = fetcher.cachedLookupDepartures(station, arrival, type);
95                            beans.arrival = arrival;
96                  } catch (java.io.IOException ioe) {                  } catch (java.io.IOException ioe) {
97                          logger.warning("Read failed, station="+station + ". " + ioe.getMessage() );                          logger.warning("Read failed, station="+station + ". " + ioe.getMessage() );
98                          Statistics.getInstance().incrementDepartureErrors();                          Statistics.getInstance().incrementDepartureErrors();
99                          resp.sendError(500);                          resp.sendError(500);
100                          return;                          return;
101                  } catch (CircuitBreakerException cbe) {                  } catch (CircuitBreakerException cbe) {
102                          logger.warning("Circuitbreaker - failing fast");                          logger.warning("Circuitbreaker - failing fast, station=" +station);
103                          Statistics.getInstance().incrementDepartureErrors();                          Statistics.getInstance().incrementDepartureErrors();
104                          resp.sendError(500);                          resp.sendError(500);
105                          return;                          return;
106                    } catch (StationDAO.NostationException nse) {
107                            logger.log(Level.WARNING, "Station not in Database, station=" +station);
108                            Statistics.getInstance().incrementDepartureErrors();
109                            resp.sendError(400, "invalid station ID");
110                            return;                
111                  } catch (Exception e) {                                  } catch (Exception e) {                
112                          logger.log(Level.WARNING, "Unknown exception, station=" +station, e);                          logger.log(Level.WARNING, "Unknown exception, station=" +station, e);
113                          Statistics.getInstance().incrementDepartureErrors();                          Statistics.getInstance().incrementDepartureErrors();
# Line 92  public class DepartureServlet extends Ht Line 120  public class DepartureServlet extends Ht
120                                    
121                  if (format.equalsIgnoreCase("xml")) {                  if (format.equalsIgnoreCase("xml")) {
122                          resp.setContentType("text/xml");                          resp.setContentType("text/xml");
123                          resp.getWriter().print( formatXml(beans, arrival) );                          resp.getWriter().print( formatXml(beans) );
124                  } else if (format.equalsIgnoreCase("html")) {                  } else if (format.equalsIgnoreCase("html")) {
125                                                    
126                          String advStr = req.getParameter("advanced");                          String advStr = req.getParameter("advanced");
# Line 102  public class DepartureServlet extends Ht Line 130  public class DepartureServlet extends Ht
130                          req.setAttribute("departurebeans", beans);                          req.setAttribute("departurebeans", beans);
131                          req.setAttribute("stationID", station );                          req.setAttribute("stationID", station );
132                          getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);                          getServletContext().getRequestDispatcher("/ViewDepartures.jsp").forward(req,resp);
133                            /*resp.setContentType("text/html");
134                            resp.getWriter().print(  xmlToHtml(formatXml(beans))  );*/
135                  } else {                  } else {
136                          resp.sendError(400, "Unknown format");                                            resp.sendError(400, "Unknown format");                  
137                  }                  }
138    
139          }          }
140    
141          protected String formatXml(DepartureBean beans, boolean arrival) throws ServletException{          protected String formatXml(DepartureBean beans) throws ServletException{
142                  String xml = "";                  
143                  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", beans.getStationName());  
                 root.setAttribute("arrival", Boolean.toString(arrival) );  
                   
                 for (String notif : beans.notifications) {  
                         Element notElem = doc.createElement("notification");  
                         notElem.setTextContent(notif);  
                         root.appendChild(notElem);  
                 }  
                   
                 for (DepartureEntry departure : beans.departureEntries) {  
                         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);  
                           
                         Element type = doc.createElement("type");  
                         type.setTextContent( departure.getType() );  
                         train.appendChild(type);  
                           
                         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", "1");  
                 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();  
144    
145                    StringWriter out = new StringWriter();
146    
147                    try {
148                            serializer.write(beans, out);
149                  } catch (Exception e) {                  } catch (Exception e) {
150                          throw new ServletException(e);                          throw new ServletException(e);
151                  }                  }
152                  return xml;                  
153                    return out.toString();
154          }          }
155            /*
156            protected String xmlToHtml(String input) throws ServletException {
157    
158                    try {                                  
159                            Transformer trans = xslTemplate.newTransformer();
160                            
161                    
162                            Source xml = new StreamSource( new StringReader(input));
163                            StringWriter out = new StringWriter();
164                            trans.transform(xml, new StreamResult(out));            
165                    
166                            return out.toString();
167                    } catch (Exception e) {
168                            throw new ServletException(e);
169                    }
170            }*/
171    
172  }  }

Legend:
Removed from v.1026  
changed lines
  Added in v.1253

  ViewVC Help
Powered by ViewVC 1.1.20