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

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

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

android/TrainInfoService/src/dk/thoerup/traininfoservice/StationDAO.java revision 1082 by torben, Tue Sep 21 05:55:31 2010 UTC android/TrainInfoService/src/dk/thoerup/traininfoservice/db/StationDAO.java revision 1515 by torben, Fri Jun 10 08:25:43 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice;  package dk.thoerup.traininfoservice.db;
2    
3  import java.sql.Array;  import java.sql.Array;
4  import java.sql.Connection;  import java.sql.Connection;
# Line 9  import java.sql.Statement; Line 9  import java.sql.Statement;
9  import java.util.logging.Logger;  import java.util.logging.Logger;
10    
11  import dk.thoerup.android.traininfo.common.StationBean;  import dk.thoerup.android.traininfo.common.StationBean;
12  import dk.thoerup.android.traininfo.common.StationBean.StationEntry;  import dk.thoerup.android.traininfo.common.StationEntry;
13    
14  public class StationDAO {  public class StationDAO {
15            
16            private interface StatementParamSetter {
17                    public void setParams(PreparedStatement stmt) throws SQLException ;
18            }
19            private class NullSetter implements StatementParamSetter {
20                    @Override
21                    public void setParams(PreparedStatement stmt) throws SQLException {}
22            }
23            
24            public static class NostationException extends Exception {
25                    private static final long serialVersionUID = 1L;
26            }
27            
28          final static int LOCATION_LIMIT = 8;          final static int LOCATION_LIMIT = 8;
29          static final Logger logger = Logger.getLogger(StationDAO.class.getName());          static final Logger logger = Logger.getLogger(StationDAO.class.getName());
30                    
# Line 45  public class StationDAO { Line 58  public class StationDAO {
58    
59          }          }
60    
61            private StationBean fetchStations(String SQL, StatementParamSetter setter) throws SQLException {
62          public StationEntry getById(int id) throws SQLException {                  StationBean stations;
                 String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0 " +  
                 "FROM trainstations WHERE id=" + id + " AND enabled=true";  
   
63                  Connection conn = null;                  Connection conn = null;
64                  Statement stmt = null;                  PreparedStatement stmt = null;
65                  ResultSet res = null;                  ResultSet res = null;
                 StationEntry result;  
   
66                  try {                  try {
67                          conn = DBConnection.getConnection();                          conn = DBConnection.getConnection();
68                            stmt = conn.prepareStatement(SQL);
69                            
70                            setter.setParams(stmt);
71    
72                            res = stmt.executeQuery();
73                            stations = convertResultset(res);
74    
                         stmt = conn.createStatement();  
                         res = stmt.executeQuery(SQL);            
                         res.next();  
                         result = convertSingleRow(res);  
75                  } finally {                  } finally {
76                          if (res != null)                          if (res != null)
77                                  res.close();                                  res.close();
78                          if (stmt != null)                          if (stmt != null)
79                                  stmt.close();                                  stmt.close();
80                          if (conn != null)                          if (conn!= null)
81                                  conn.close();                                  conn.close();
82                  }                  }
83                    return stations;
                 return result;  
         }  
           
         public StationBean dumpAll() throws SQLException {  
                   
                 String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0,aliases " +  
                                 "FROM trainstations WHERE enabled = true ORDER BY id";  
                   
                 Connection conn = null;  
                 Statement stmt = null;  
                 ResultSet res = null;            
   
84                                    
85                  try {          }
                         conn = DBConnection.getConnection();  
86    
87                          stmt = conn.createStatement();          public StationEntry getById(int id) throws SQLException,NostationException {
88                          res = stmt.executeQuery(SQL);                            String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0 " +
89                                                                    "FROM trainstations WHERE id=" + id + " AND enabled=true";
                         // Does mostly the same as convertResultset()  
                         StationBean stations = new StationBean();  
                         while (res.next()) {  
                                 StationEntry entry = convertSingleRow(res);  
                                   
                                 Array arr = res.getArray(10);  
                                 if (arr != null) {  
                                         String[] aliases = (String[]) arr.getArray();  
                                         entry.setAliases(aliases);  
                                 }  
                                   
                                 stations.entries.add( entry );  
90                                                                    
91                          }                  StationBean stations =  fetchStations(SQL, new NullSetter() );
                         return stations;  
                           
   
                 } finally {  
                         if (res != null)  
                                 res.close();  
                         if (stmt != null)  
                                 stmt.close();  
                         if (conn != null)  
                                 conn.close();  
                 }  
92                                    
93                    if (stations.entries.size() > 0 ) {
94                            return stations.entries.get(0);
95                    } else {
96                            throw new NostationException();
97                    }
98          }          }
99            
100    
101    
102          /*          /*
103           * 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) )
# Line 124  public class StationDAO { Line 105  public class StationDAO {
105           *     'select $2 ilike $1' language sql strict immutable;           *     'select $2 ilike $1' language sql strict immutable;
106           *     create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~);           *     create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~);
107           */           */
108          public StationBean getByName(String name) throws SQLException {          public StationBean getByNameNormal(final String name) throws SQLException {
109                  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 " +
110                  "FROM trainstations " +                  "FROM trainstations " +
111                  "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " +                  "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " +
112                  "ORDER BY name ";                  "ORDER BY name ";
113    
114                    class NameSetter implements StatementParamSetter {
115                            @Override
116                            public void setParams(PreparedStatement stmt) throws SQLException {
117                                    stmt.setString(1, name + "%");
118                                    stmt.setString(2, name + "%");                          
119                            }                      
120                    }
121                    
122                    return fetchStations(SQL, new NameSetter() );
123            }
124            
125            
126            public StationBean getByNameFuzzy(final String name) throws SQLException {
127                    String SQL = "SELECT * FROM (" +
128                                             "    SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0, " +
129                                             "    levenshtein(lower(name),lower(?) ) as leven " +
130                                             "    FROM trainstations " +
131                                             "    WHERE  enabled = true ) as lev2 " +
132                                             "WHERE (leven <= 3) " +                
133                                             "ORDER BY leven " +
134                                             "LIMIT 1";
135    
136                    class NameSetter implements StatementParamSetter {
137                            @Override
138                            public void setParams(PreparedStatement stmt) throws SQLException {
139                                    stmt.setString(1, name );
140                            }                      
141                    }
142                    
143                    StationBean stations = fetchStations(SQL, new NameSetter() );
144                    stations.fuzzystrmatch = true;
145                    return stations;
146            }
147            
148            public StationBean getByName(String name) throws SQLException {
149                    StationBean stations = getByNameNormal(name);
150                    
151                    if (stations.entries.size() == 0) {
152                            name = name.replace(".", ""); //remove any .'s before fuzzy search
153                            stations = getByNameFuzzy(name);
154    
155                  StationBean result;                          logger.info("getByName failover: " + name + "(" + (stations.entries.size() >0) + ")" );
                 Connection conn = null;  
                 PreparedStatement stmt = null;  
                 ResultSet res = null;  
                 try {  
                         conn = DBConnection.getConnection();  
                         stmt = conn.prepareStatement(SQL);  
   
                         stmt.setString(1, name + "%");  
                         stmt.setString(2, name + "%");  
   
                         res = stmt.executeQuery();  
                         result = convertResultset(res);  
   
                 } finally {  
                         if (res != null)  
                                 res.close();  
                         if (stmt != null)  
                                 stmt.close();  
                         if (conn!= null)  
                                 conn.close();  
156                  }                  }
157                  return result;                  return stations;
158          }          }
159            
160            
161    
162          //the "hack" with max 0.4 degrees latitude and 0.75 degrees longitude is only valid since we only service danish trains,          //Latitude (horizonal), longitude(vertical) so
163            // 1 degree latitude is ~ 111320 meters, since the distance between the horizonal lines is always the same
164            // 1 degree longitude is ~111320 meters at equator but gets shorter as we get closer to the poles.
165            // so 1 degree longitude is 64.5 km at denmarks southern point (gedser=54.55,11.95)
166            // and is 59.4km at northern point (skagen = 57.75,10.65)
167            // The "hack" with max 0.4 degrees latitude and 0.75 degrees longitude is only valid since we only service danish trains,
168          // in denmark 0.4dg latitude ~ 44km, 0.75dg longitude ~ 47km          // in denmark 0.4dg latitude ~ 44km, 0.75dg longitude ~ 47km
169    
170          // the ultra fast method  (and only slightly inaccurate as long as we only cover a limited geographically area)          // the ultra fast method  (and only slightly inaccurate as long as we only cover a limited geographically area)
# Line 164  public class StationDAO { Line 172  public class StationDAO {
172          // calculate the distance:          // calculate the distance:
173          //     sqrt( power(abs(latitude-?)*111320, 2) + power(abs(longitude-?)*63000,2) )::int as calcdist          //     sqrt( power(abs(latitude-?)*111320, 2) + power(abs(longitude-?)*63000,2) )::int as calcdist
174    
175          public StationBean getByLocationWorker(double latitude, double longitude, boolean geolimit) throws SQLException {          public StationBean getByLocationWorker(final double latitude, final double longitude, final boolean geolimit) throws SQLException {
176                                    
177                  String limitExpression = (geolimit == true) ? "AND abs(latitude-?)<0.4 AND abs(longitude-?)<0.75 " : "";                  String limitExpression = (geolimit == true) ? "AND abs(latitude-?)<0.4 AND abs(longitude-?)<0.75 " : "";
178                                    
# Line 175  public class StationDAO { Line 183  public class StationDAO {
183                          "ORDER BY calcdist ASC " +                          "ORDER BY calcdist ASC " +
184                          "LIMIT " + LOCATION_LIMIT;                          "LIMIT " + LOCATION_LIMIT;
185    
   
186                                    
187                  StationBean result;                  class LatlongSetter implements StatementParamSetter {
188                  Connection conn = null;                          @Override
189                  PreparedStatement stmt = null;                          public void setParams(PreparedStatement stmt) throws SQLException {
190                  ResultSet res = null;                                  stmt.setDouble(1, latitude);
191                  try {                                  stmt.setDouble(2, longitude);
192                          conn = DBConnection.getConnection();                                  if (geolimit == true) {
193                          stmt = conn.prepareStatement(SQL);                                          stmt.setDouble(3, latitude);
194                          stmt.setDouble(1, latitude);                                          stmt.setDouble(4, longitude);
195                          stmt.setDouble(2, longitude);                                  }                              
196                          if (geolimit == true) {                          }                      
                                 stmt.setDouble(3, latitude);  
                                 stmt.setDouble(4, longitude);  
                         }  
                         res = stmt.executeQuery();  
                         result = convertResultset(res);  
                   
                 } finally {  
                         if (res != null)  
                                 res.close();  
                         if (stmt != null)  
                                 stmt.close();  
                         if (conn!= null)  
                                 conn.close();  
197                  }                  }
198                  return result;                  
199                    return fetchStations(SQL, new LatlongSetter() );
200          }          }
201                    
202          public StationBean getByLocation(double latitude, double longitude) throws SQLException {          public StationBean getByLocation(double latitude, double longitude) throws SQLException {
# Line 223  public class StationDAO { Line 218  public class StationDAO {
218                  "FROM trainstations " +                  "FROM trainstations " +
219                  "WHERE id IN " + list + " AND enabled = true " +                  "WHERE id IN " + list + " AND enabled = true " +
220                  "ORDER BY name ";                  "ORDER BY name ";
221                    
222                    return fetchStations(SQL, new NullSetter() );
223            }
224            
225    
226            
227            public StationEntry getSimpleByName(final String name) throws SQLException {
228                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " +
229                    "FROM trainstations " +
230                    "WHERE name = ?  AND enabled = true " +
231                    "LIMIT 1 ";
232    
233                    class NameSetter implements StatementParamSetter {
234                            @Override
235                            public void setParams(PreparedStatement stmt) throws SQLException {
236                                    stmt.setString(1, name );
237                            }                      
238                    }
239                    
240                    StationBean stations = fetchStations(SQL, new NameSetter() );
241                    
242                    if (stations.entries.size() == 1) {
243                            return stations.entries.get(0);
244                    } else {
245                            return null;
246                    }
247            }
248            
249            //used to create full dump in order to populate Google Appengine DB
250            @Deprecated
251            public StationBean dumpAll() throws SQLException {
252                    
253                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0,aliases " +
254                                    "FROM trainstations WHERE enabled = true ORDER BY id";
255                    
256                  Connection conn = null;                  Connection conn = null;
257                  Statement stmt = null;                  Statement stmt = null;
258                  ResultSet res = null;                  ResultSet res = null;          
                 StationBean result;  
259    
260                    
261                  try {                  try {
262                          conn = DBConnection.getConnection();                          conn = DBConnection.getConnection();
263    
264                          stmt = conn.createStatement();                          stmt = conn.createStatement();
265                          res = stmt.executeQuery(SQL);                          res = stmt.executeQuery(SQL);          
266                          result = convertResultset(res);                                                  
267                            // Does mostly the same as convertResultset()
268                            StationBean stations = new StationBean();
269                            while (res.next()) {
270                                    StationEntry entry = convertSingleRow(res);
271                                    
272                                    Array arr = res.getArray(10);
273                                    if (arr != null) {
274                                            String[] aliases = (String[]) arr.getArray();
275                                            entry.setAliases(aliases);
276                                    }
277                                    
278                                    stations.entries.add( entry );
279                                    
280                            }
281                            return stations;
282                            
283    
284                  } finally {                  } finally {
285                          if (res != null)                          if (res != null)
286                                  res.close();                                  res.close();
287                          if (stmt != null)                          if (stmt != null)
288                                  stmt.close();                                  stmt.close();
289                          if (conn!= null)                          if (conn != null)
290                                  conn.close();                                  conn.close();
291                  }                  }
292                    
                 return result;  
   
293          }          }
294    
295            @Deprecated
296          public static String getStationName(int stationID) {          public static String getStationName(int stationID) {
297                  String station = "";                  String station = "";
298    
# Line 268  public class StationDAO { Line 315  public class StationDAO {
315    
316                  return station;                  return station;
317          }          }
318            
319          public int getIdByName(String name) throws SQLException {          
320            
321            @Deprecated
322            public int getIdByName(final String name) throws SQLException {
323                  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 " +
324                  "FROM trainstations " +                  "FROM trainstations " +
325                  "WHERE name = ?  AND enabled = true " +                  "WHERE name = ?  AND enabled = true " +
326                  "LIMIT 1 ";                  "LIMIT 1 ";
327    
328                  StationBean result;                  class NameSetter implements StatementParamSetter {
329                  Connection conn = null;                          @Override
330                  PreparedStatement stmt = null;                          public void setParams(PreparedStatement stmt) throws SQLException {
331                  ResultSet res = null;                                  stmt.setString(1, name );
332                  try {                          }                      
                         conn = DBConnection.getConnection();  
                         stmt = conn.prepareStatement(SQL);  
   
                         stmt.setString(1, name );  
   
                         res = stmt.executeQuery();  
                         result = convertResultset(res);  
   
                 } finally {  
                         if (res != null)  
                                 res.close();  
                         if (stmt != null)  
                                 stmt.close();  
                         if (conn!= null)  
                                 conn.close();  
333                  }                  }
334                    
335                  if (result.entries.size() == 1) {                  StationBean stations = fetchStations(SQL, new NameSetter() );
336                          return result.entries.get(0).getId();                  
337                    if (stations.entries.size() == 1) {
338                            return stations.entries.get(0).getId();
339                  } else {                  } else {
340                          return -1;                          return -1;
341                  }                  }

Legend:
Removed from v.1082  
changed lines
  Added in v.1515

  ViewVC Help
Powered by ViewVC 1.1.20