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

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

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

revision 305 by torben, Thu Sep 10 09:40:27 2009 UTC revision 389 by torben, Fri Oct 2 17:18:31 2009 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice.banedk;  package dk.thoerup.traininfoservice.banedk;
2    
3    import java.sql.Connection;
4    import java.sql.ResultSet;
5    import java.sql.Statement;
6  import java.util.ArrayList;  import java.util.ArrayList;
7    import java.util.Collections;
8  import java.util.List;  import java.util.List;
9    import java.util.logging.Logger;
10    
11    
 import com.gargoylesoftware.htmlunit.ProxyConfig;  
12  import com.gargoylesoftware.htmlunit.WebClient;  import com.gargoylesoftware.htmlunit.WebClient;
13  import com.gargoylesoftware.htmlunit.html.DomNodeList;  import com.gargoylesoftware.htmlunit.html.DomNodeList;
14  import com.gargoylesoftware.htmlunit.html.HtmlElement;  import com.gargoylesoftware.htmlunit.html.HtmlElement;
15  import com.gargoylesoftware.htmlunit.html.HtmlPage;  import com.gargoylesoftware.htmlunit.html.HtmlPage;
16    
17    import dk.thoerup.traininfoservice.DBConnection;
18    
19  public class DepartureFetcher {  public class DepartureFetcher {
20                    
21            Logger logger = Logger.getLogger(DepartureFetcher.class.getName());
22            
23            TimeoutCache<Integer, List<DepartureBean>> cache = new TimeoutCache<Integer,List<DepartureBean>>(120 * 1000);
24            
25                    
26                    
27          static ProxyConfig proxyConfig;          public List<DepartureBean> cachedLookupDepartures(int stationID) throws Exception {
28          static {  
29                  proxyConfig = new ProxyConfig();                  List<DepartureBean> list = cache.get(stationID);
30                  proxyConfig.setProxyHost("rafiki.t-hoerup.dk");                  
31                  proxyConfig.setProxyPort(3128);                  if (list == null) {
32                            list = lookupDepartures(stationID);
33                            cache.put(stationID, list);
34                    } else {
35                            logger.info("Departure: Cache hit " + stationID); //remove before production
36                    }
37                    return list;
38            }
39                    
40    
41            public List<DepartureBean> lookupDepartures(int stationID) throws Exception {
42                    List<DepartureBean> departureList = new ArrayList<DepartureBean>();
43                    
44                    Connection conn = null;
45                    try
46                    {
47                            conn = DBConnection.getConnection();
48                    
49                            String SQL = "SELECT stationcode_fjrn, stationcode_stog FROM trainstations WHERE id=" + stationID;
50                            Statement stmt = conn.createStatement();
51                            ResultSet rs = stmt.executeQuery(SQL);
52                            
53                            if (rs.next()) {
54                                    String code = rs.getString( 1 );
55                                    if (! rs.wasNull() ) {
56                                            List<DepartureBean> list = lookupDepartures(code, "FJRN");
57                                            departureList.addAll(list);
58                                    }
59                                    
60                                    code = rs.getString(2);
61                                    if (! rs.wasNull() ) {
62                                            List<DepartureBean> list = lookupDepartures(code, "S2");
63                                            departureList.addAll(list);    
64                                    }
65                                    Collections.sort( departureList );
66                            
67                            }
68                            
69                    } finally {
70                            if (conn != null && !conn.isClosed() ) {
71                                    conn.close();
72                            }
73                    }
74                    
75                    return departureList;
76          }          }
77                    
78          public List<DepartureBean> lookupDepartures() throws Exception {          public List<DepartureBean> lookupDepartures(String stationcode, String type) throws Exception {
79                                    
80                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();                  List<DepartureBean> departureList = new ArrayList<DepartureBean>();
81                                    
82              final WebClient webClient = new WebClient();              final WebClient webClient = new WebClient();
83              webClient.setTimeout(1000);              webClient.setTimeout(2500);
84              webClient.setProxyConfig(proxyConfig);              webClient.setJavaScriptEnabled(false);
85              webClient.setJavaScriptEnabled(false);                              
86                            
87              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=FJRN&S=BJ");              final HtmlPage page = webClient.getPage("http://www.bane.dk/visStation.asp?ArtikelID=4275&W=" + type + "&S=" + stationcode);
88                            
89              HtmlElement table = page.getElementById("afgangtabel");              HtmlElement table = page.getElementById("afgangtabel");
             DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");  
90                            
91              for (HtmlElement currentRow : tableRows) {              if (table != null) {
92                  String rowClass = currentRow.getAttribute("class");                      DomNodeList<HtmlElement> tableRows =  table.getElementsByTagName("tr");
93                  if (rowClass != null && rowClass.toLowerCase().contains("station") ) {                      
94                          DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");                      for (HtmlElement currentRow : tableRows) {
95                            String rowClass = currentRow.getAttribute("class");
96                          DepartureBean departure = new DepartureBean();                          if (rowClass != null && rowClass.toLowerCase().contains("station") ) {
97                                                            DomNodeList<HtmlElement> fields = currentRow.getElementsByTagName("td");
98                          String time = fields.get(0).asText();          
99                          departure.setTime(time);                                  DepartureBean departure = new DepartureBean();
100                                                            
101                          int updated = extractUpdated( fields.get(1) );                                  String time = fields.get(0).asText();
102                          departure.setUpdated(updated);                                  if (time.equals(""))
103                                                                    time = "0:00"; //Bane.dk bug work-around
104                          String trainNumber = fields.get(2).asText();                                  departure.setTime(time);
105                          departure.setTrainNumber(trainNumber);                                  
106                                                            int updated = extractUpdated( fields.get(1) );
107                          String destination = fields.get(3).asText();                                  departure.setUpdated(updated);
108                          departure.setDestination(destination);                                  
109                                                            String trainNumber = fields.get(2).asText();
110                          String origin = fields.get(4).asText();                                  if (trainNumber.trim().length() == 1)
111                          departure.setOrigin(origin);                                          trainNumber = trainNumber + " " + extractTrainNumber(fields.get(2));
112                                                            departure.setTrainNumber(trainNumber);
113                          String location = fields.get(5).asText();                                  
114                          departure.setLocation(location);                                  String destination = fields.get(3).asText();
115                                                            departure.setDestination(destination);
116                          String status = fields.get(6).asText();                                  
117                          departure.setStatus(status);                                  String origin = fields.get(4).asText();
118                                                            departure.setOrigin(origin);
119                          String note = fields.get(7).asText();                                  
120                          departure.setNote(note);                                  String location = fields.get(5).asText();
121                                                            departure.setLocation(location);
122                          departureList.add(departure);                                  
123                  }                                  String status = fields.get(6).asText();
124                                    departure.setStatus(status);
125                                    
126                                    String note = extractNote( fields.get(7) );
127                                    departure.setNote(note);
128                                    
129                                    departureList.add(departure);
130                            }
131                        }
132                } else {
133                    logger.warning("No departures found for station=" + stationcode + ", type=" + type);
134              }              }
135                            
136              return departureList;              return departureList;
# Line 89  public class DepartureFetcher { Line 154  public class DepartureFetcher {
154                  return updated;                  return updated;
155          }          }
156                    
157            private String extractNote(HtmlElement noteTd) {
158                    String note = noteTd.asText().trim();
159                    
160                    List<HtmlElement> elems = noteTd.getElementsByAttribute("span", "class", "bemtype");
161                    if (elems.size() > 0 && note.charAt(note.length()-1) == 'i')
162                            note = note.substring(0,note.length() -1 );
163    
164                    return note;
165            }
166            
167            private String extractTrainNumber(HtmlElement trainTd) {
168                    String number = "";
169                    HtmlElement anchorElement = trainTd.getElementsByTagName("a").get(0);
170                    String href = anchorElement.getAttribute("href");
171                    String argstring = href.substring( href.indexOf('?') + 1);
172                    
173                    String args[] = argstring.split("&");
174                    for (String arg : args) {
175                            String pair[] = arg.split("="); // Key=pair[0], Value=pair[1]
176                            
177                            if (pair[0].equalsIgnoreCase("TogNr"))
178                                    number = pair[1];
179                    }
180                    
181                    
182                    
183                    return number;
184            }
185            
186          //test          //test
187          public static void main(String args[]) throws Exception{          public static void main(String args[]) throws Exception{
188                  DepartureFetcher f = new DepartureFetcher();                  DepartureFetcher f = new DepartureFetcher();
189                  List<DepartureBean> deps = f.lookupDepartures();                  List<DepartureBean> deps = f.lookupDepartures("AR", "FJRN");
190                  for(DepartureBean d : deps) {                  for(DepartureBean d : deps) {
191                          System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +                          System.out.println( d.getTime() + ";" + d.getUpdated() + ";" + d.getTrainNumber() + ";" +
192                                                  d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote()   );                                                  d.getDestination() + ";" + d.getOrigin() + ";" + d.getLocation() + ";" + d.getStatus() + ";" + d.getNote()   );

Legend:
Removed from v.305  
changed lines
  Added in v.389

  ViewVC Help
Powered by ViewVC 1.1.20