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

Diff of /android/TrainInfoService/src/dk/thoerup/traininfoservice/StationDAO.java

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

revision 733 by torben, Tue May 18 17:56:43 2010 UTC revision 1145 by torben, Fri Oct 1 05:30:32 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice;  package dk.thoerup.traininfoservice;
2    
3    import java.sql.Array;
4  import java.sql.Connection;  import java.sql.Connection;
5  import java.sql.PreparedStatement;  import java.sql.PreparedStatement;
6  import java.sql.ResultSet;  import java.sql.ResultSet;
7  import java.sql.SQLException;  import java.sql.SQLException;
8  import java.sql.Statement;  import java.sql.Statement;
9  import java.util.ArrayList;  import java.util.logging.Logger;
10  import java.util.List;  
11    import dk.thoerup.android.traininfo.common.StationBean;
12    import dk.thoerup.android.traininfo.common.StationBean.StationEntry;
13    
14  public class StationDAO {  public class StationDAO {
15          private StationBean convertSingleRow(ResultSet res) throws SQLException {          
16                  StationBean station = new StationBean();          public static class NostationException extends Exception {
17                                    private static final long serialVersionUID = 1L;
18            }
19            
20            final static int LOCATION_LIMIT = 8;
21            static final Logger logger = Logger.getLogger(StationDAO.class.getName());
22            
23            
24            private StationEntry convertSingleRow(ResultSet res) throws SQLException {
25                    StationEntry station = new StationEntry();
26    
27                  station.setId( res.getInt(1) );                  station.setId( res.getInt(1) );
28                  station.setName( res.getString(2) );                  station.setName( res.getString(2) );
29                  station.setLatitude( res.getDouble(3) );                  station.setLatitude( res.getDouble(3) );
# Line 22  public class StationDAO { Line 34  public class StationDAO {
34                  station.setAddress( res.getString(8) );                  station.setAddress( res.getString(8) );
35                  station.setCalcdist( (int)res.getDouble(9) );                  station.setCalcdist( (int)res.getDouble(9) );
36                                    
37                    station.setIsRegional( station.getRegional() != null );
38                    station.setIsStrain( station.getStrain() != null );
39                    station.setIsMetro( station.getMetro() != null );
40    
41                  return station;                  return station;
42          }          }
43            
44          private List<StationBean> convertResultset(ResultSet res) throws SQLException {          private StationBean convertResultset(ResultSet res) throws SQLException {
45                  List<StationBean> stations = new ArrayList<StationBean>();                  StationBean stations = new StationBean();
46                  while (res.next()) {                  while (res.next()) {
47                          stations.add( convertSingleRow(res) );                          stations.entries.add( convertSingleRow(res) );
48                  }                  }
49                  return stations;                  return stations;
50                    
51          }          }
52            
53            
54          public StationBean getById(int id) throws SQLException {          public StationEntry getById(int id) throws SQLException,NostationException {
55                  String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0 " +                  String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0 " +
56                        "FROM trainstations WHERE id=" + id + " AND enabled=true";                  "FROM trainstations WHERE id=" + id + " AND enabled=true";
57                    
58                  Connection conn = null;                  Connection conn = null;
59                  Statement stmt = null;                  Statement stmt = null;
60                  ResultSet res = null;                  ResultSet res = null;
61                  StationBean result;                  StationEntry result;
62                    
63                  try {                  try {
64                          conn = DBConnection.getConnection();                          conn = DBConnection.getConnection();
65    
66                            stmt = conn.createStatement();
67                            res = stmt.executeQuery(SQL);
68                            
69                            if (res.next()) {
70                                    result = convertSingleRow(res);
71                            } else {
72                                    throw new NostationException();
73                            }
74                    } finally {
75                            if (res != null)
76                                    res.close();
77                            if (stmt != null)
78                                    stmt.close();
79                            if (conn != null)
80                                    conn.close();
81                    }
82    
83                    return result;
84            }
85            
86            public StationBean dumpAll() throws SQLException {
87                    
88                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0,aliases " +
89                                    "FROM trainstations WHERE enabled = true ORDER BY id";
90                    
91                    Connection conn = null;
92                    Statement stmt = null;
93                    ResultSet res = null;          
94    
95                                    
96                    try {
97                            conn = DBConnection.getConnection();
98    
99                          stmt = conn.createStatement();                          stmt = conn.createStatement();
100                          res = stmt.executeQuery(SQL);                                    res = stmt.executeQuery(SQL);          
101                          res.next();                                                  
102                          result = convertSingleRow(res);                          // Does mostly the same as convertResultset()
103                            StationBean stations = new StationBean();
104                            while (res.next()) {
105                                    StationEntry entry = convertSingleRow(res);
106                                    
107                                    Array arr = res.getArray(10);
108                                    if (arr != null) {
109                                            String[] aliases = (String[]) arr.getArray();
110                                            entry.setAliases(aliases);
111                                    }
112                                    
113                                    stations.entries.add( entry );
114                                    
115                            }
116                            return stations;
117                            
118    
119                  } finally {                  } finally {
120                          if (res != null)                          if (res != null)
121                                  res.close();                                  res.close();
# Line 60  public class StationDAO { Line 125  public class StationDAO {
125                                  conn.close();                                  conn.close();
126                  }                  }
127                                    
                 return result;  
128          }          }
129            
130          /*          /*
131           * this code requires theses statements are run on database in order to do ILIKE searches against aliases (which is defines as array of varchar(64) )           * this code requires theses statements are run on database in order to do ILIKE searches against aliases (which is defines as array of varchar(64) )
132           *     create function rlike(text,text) returns bool as           *     create function rlike(text,text) returns bool as
133           *     'select $2 ilike $1' language sql strict immutable;           *     'select $2 ilike $1' language sql strict immutable;
134       *     create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~);           *     create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~);
135           */           */
136          public List<StationBean> getByName(String name) throws SQLException {          public StationBean getByName(String name) throws SQLException {
137                  String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " +                  String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " +
138                  "FROM trainstations " +                  "FROM trainstations " +
139                  "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " +                  "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " +
140                  "ORDER BY name ";                  "ORDER BY name ";
141    
142                    
143                  List<StationBean> result;                  StationBean result;
144                  Connection conn = null;                  Connection conn = null;
145                  PreparedStatement stmt = null;                  PreparedStatement stmt = null;
146                  ResultSet res = null;                  ResultSet res = null;
147                  try {                  try {
148                          conn = DBConnection.getConnection();                          conn = DBConnection.getConnection();
149                          stmt = conn.prepareStatement(SQL);                          stmt = conn.prepareStatement(SQL);
150                            
151                          stmt.setString(1, name + "%");                          stmt.setString(1, name + "%");
152                          stmt.setString(2, name + "%");                          stmt.setString(2, name + "%");
153                            
154                          res = stmt.executeQuery();                          res = stmt.executeQuery();
155                          result = convertResultset(res);                          result = convertResultset(res);
156                            
157                  } finally {                  } finally {
158                          if (res != null)                          if (res != null)
159                                  res.close();                                  res.close();
# Line 100  public class StationDAO { Line 164  public class StationDAO {
164                  }                  }
165                  return result;                  return result;
166          }          }
167            
168          public List<StationBean> getByLocation(double latitude, double longitude) throws SQLException {          //the "hack" with max 0.4 degrees latitude and 0.75 degrees longitude is only valid since we only service danish trains,
169                  String SQL = "SELECT * FROM ( "+          // in denmark 0.4dg latitude ~ 44km, 0.75dg longitude ~ 47km
170                  "               SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address," +  
171                  "                     earth_distance( earth_coord, ll_to_earth(?,?))::int AS calcdist " +          // the ultra fast method  (and only slightly inaccurate as long as we only cover a limited geographically area)
172                  "               FROM trainstations " +          // is using an aproximation of the length of 1 latitude degree and 1 longitude degree and just use pythagoras to
173                  "               WHERE enabled = true " +          // calculate the distance:
174                  "       ) AS trainstations2 " +          //     sqrt( power(abs(latitude-?)*111320, 2) + power(abs(longitude-?)*63000,2) )::int as calcdist
175                  "ORDER BY calcdist ASC " +  
176                  "LIMIT 4 ";          public StationBean getByLocationWorker(double latitude, double longitude, boolean geolimit) throws SQLException {
177                  List<StationBean> result;                  
178                    String limitExpression = (geolimit == true) ? "AND abs(latitude-?)<0.4 AND abs(longitude-?)<0.75 " : "";
179                    
180                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, " +
181                            "earth_distance( earth_coord, ll_to_earth(?,?))::int AS calcdist " +
182                            "FROM trainstations " +
183                            "WHERE enabled = true " + limitExpression +
184                            "ORDER BY calcdist ASC " +
185                            "LIMIT " + LOCATION_LIMIT;
186    
187    
188                    
189                    StationBean result;
190                  Connection conn = null;                  Connection conn = null;
191                  PreparedStatement stmt = null;                  PreparedStatement stmt = null;
192                  ResultSet res = null;                  ResultSet res = null;
# Line 119  public class StationDAO { Line 195  public class StationDAO {
195                          stmt = conn.prepareStatement(SQL);                          stmt = conn.prepareStatement(SQL);
196                          stmt.setDouble(1, latitude);                          stmt.setDouble(1, latitude);
197                          stmt.setDouble(2, longitude);                          stmt.setDouble(2, longitude);
198                            if (geolimit == true) {
199                                    stmt.setDouble(3, latitude);
200                                    stmt.setDouble(4, longitude);
201                            }
202                          res = stmt.executeQuery();                          res = stmt.executeQuery();
203                          result = convertResultset(res);                          result = convertResultset(res);
204                                            
205                  } finally {                  } finally {
206                          if (res != null)                          if (res != null)
207                                  res.close();                                  res.close();
# Line 132  public class StationDAO { Line 212  public class StationDAO {
212                  }                  }
213                  return result;                  return result;
214          }          }
215                    
216           public List<StationBean> getByList(String list) throws SQLException {          public StationBean getByLocation(double latitude, double longitude) throws SQLException {
217                          String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro, address,0.0 " +                  StationBean result = getByLocationWorker(latitude, longitude, true);
218                          "FROM trainstations " +                  
219                          "WHERE id IN " + list + " AND enabled = true " +                  if (result.entries.size() < LOCATION_LIMIT) { //failover
220                          "ORDER BY name ";                          logger.info("getByLocation failover: " +latitude + "," + longitude);
                           
                         Connection conn = null;  
                         Statement stmt = null;  
                         ResultSet res = null;  
                         List<StationBean> result;  
221                                                    
222                            result = getByLocationWorker(latitude, longitude, false);
223                    }
224                    
225                    return result;
226            }
227            
228            
229    
230            public StationBean getByList(String list) throws SQLException {
231                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro, address,0.0 " +
232                    "FROM trainstations " +
233                    "WHERE id IN " + list + " AND enabled = true " +
234                    "ORDER BY name ";
235    
236                    Connection conn = null;
237                    Statement stmt = null;
238                    ResultSet res = null;
239                    StationBean result;
240    
241                    try {
242                            conn = DBConnection.getConnection();
243                            stmt = conn.createStatement();
244                            res = stmt.executeQuery(SQL);
245                            result = convertResultset(res);
246                    } finally {
247                            if (res != null)
248                                    res.close();
249                            if (stmt != null)
250                                    stmt.close();
251                            if (conn!= null)
252                                    conn.close();
253                    }
254    
255                    return result;
256    
257            }
258            public static String getStationName(int stationID) {
259                    String station = "";
260    
261                    Connection conn = null;
262                    try {
263                            conn = DBConnection.getConnection();
264                            Statement stmt = conn.createStatement();
265                            ResultSet rs = stmt.executeQuery("SELECT name FROM trainstations WHERE id=" + stationID);
266                            if (rs.next()) {
267                                    station = rs.getString(1);
268                            }
269    
270                    } catch (Exception e) {
271                    } finally {
272                          try {                          try {
273                                  conn = DBConnection.getConnection();                                  if (conn != null && !conn.isClosed())
                                 stmt = conn.createStatement();  
                                 res = stmt.executeQuery(SQL);  
                                 result = convertResultset(res);  
                         } finally {  
                                 if (res != null)  
                                         res.close();  
                                 if (stmt != null)  
                                         stmt.close();  
                                 if (conn!= null)  
274                                          conn.close();                                          conn.close();
275                          }                          } catch (Exception e) {}
276                                            }
277                          return result;  
278                                            return station;
279           }          }
280           public static String getStationName(int stationID) {  
281                   String station = "";          public int getIdByName(String name) throws SQLException {
282                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " +
283                   Connection conn = null;                  "FROM trainstations " +
284                   try {                  "WHERE name = ?  AND enabled = true " +
285                           conn = DBConnection.getConnection();                  "LIMIT 1 ";
286                           Statement stmt = conn.createStatement();  
287                           ResultSet rs = stmt.executeQuery("SELECT name FROM trainstations WHERE id=" + stationID);                  StationBean result;
288                           if (rs.next()) {                  Connection conn = null;
289                                   station = rs.getString(1);                  PreparedStatement stmt = null;
290                           }                  ResultSet res = null;
291                    try {
292                   } catch (Exception e) {                                  conn = DBConnection.getConnection();
293                   } finally {                          stmt = conn.prepareStatement(SQL);
294                           try {  
295                                   if (conn != null && !conn.isClosed())                          stmt.setString(1, name );
296                                           conn.close();  
297                           } catch (Exception e) {}                          res = stmt.executeQuery();
298                   }                          result = convertResultset(res);
299    
300                    } finally {
301                            if (res != null)
302                                    res.close();
303                            if (stmt != null)
304                                    stmt.close();
305                            if (conn!= null)
306                                    conn.close();
307                    }
308    
309                   return station;                  if (result.entries.size() == 1) {
310           }                          return result.entries.get(0).getId();
311                    } else {
312                            return -1;
313                    }
314            }
315  }  }

Legend:
Removed from v.733  
changed lines
  Added in v.1145

  ViewVC Help
Powered by ViewVC 1.1.20