/[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 929 by torben, Sun Jun 27 17:07:27 2010 UTC android/TrainInfoService/src/dk/thoerup/traininfoservice/db/StationDAO.java revision 1504 by torben, Wed Jun 8 15:38:11 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice;  package dk.thoerup.traininfoservice.db;
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;
 import java.util.ArrayList;  
 import java.util.List;  
9  import java.util.logging.Logger;  import java.util.logging.Logger;
10    
11    import dk.thoerup.android.traininfo.common.StationBean;
12    import dk.thoerup.android.traininfo.common.StationEntry;
13    
14  public class StationDAO {  public class StationDAO {
15          final static int LOCATION_LIMIT = 5;          
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;
29          static final Logger logger = Logger.getLogger(StationDAO.class.getName());          static final Logger logger = Logger.getLogger(StationDAO.class.getName());
30                    
31                    
32          private StationBean convertSingleRow(ResultSet res) throws SQLException {          private StationEntry convertSingleRow(ResultSet res) throws SQLException {
33                  StationBean station = new StationBean();                  StationEntry station = new StationEntry();
34    
35                  station.setId( res.getInt(1) );                  station.setId( res.getInt(1) );
36                  station.setName( res.getString(2) );                  station.setName( res.getString(2) );
# Line 26  public class StationDAO { Line 41  public class StationDAO {
41                  station.setMetro( res.getString(7) );                  station.setMetro( res.getString(7) );
42                  station.setAddress( res.getString(8) );                  station.setAddress( res.getString(8) );
43                  station.setCalcdist( (int)res.getDouble(9) );                  station.setCalcdist( (int)res.getDouble(9) );
44                    
45                    station.setIsRegional( station.getRegional() != null );
46                    station.setIsStrain( station.getStrain() != null );
47                    station.setIsMetro( station.getMetro() != null );
48    
49                  return station;                  return station;
50          }          }
51    
52          private List<StationBean> convertResultset(ResultSet res) throws SQLException {          private StationBean convertResultset(ResultSet res) throws SQLException {
53                  List<StationBean> stations = new ArrayList<StationBean>();                  StationBean stations = new StationBean();
54                  while (res.next()) {                  while (res.next()) {
55                          stations.add( convertSingleRow(res) );                          stations.entries.add( convertSingleRow(res) );
56                  }                  }
57                  return stations;                  return stations;
58    
59          }          }
60    
61            private StationBean fetchStations(String SQL, StatementParamSetter setter) throws SQLException {
62                    StationBean stations;
63                    Connection conn = null;
64                    PreparedStatement stmt = null;
65                    ResultSet res = null;
66                    try {
67                            conn = DBConnection.getConnection();
68                            stmt = conn.prepareStatement(SQL);
69                            
70                            setter.setParams(stmt);
71    
72                            res = stmt.executeQuery();
73                            stations = convertResultset(res);
74    
75          public StationBean getById(int id) throws SQLException {                  } finally {
76                            if (res != null)
77                                    res.close();
78                            if (stmt != null)
79                                    stmt.close();
80                            if (conn!= null)
81                                    conn.close();
82                    }
83                    return stations;
84                    
85            }
86    
87            public StationEntry getById(int id) throws SQLException,NostationException {
88                  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 " +
89                  "FROM trainstations WHERE id=" + id + " AND enabled=true";                  "FROM trainstations WHERE id=" + id + " AND enabled=true";
90                                    
91                    StationBean stations =  fetchStations(SQL, new NullSetter() );
92                    
93                    if (stations.entries.size() > 0 ) {
94                            return stations.entries.get(0);
95                    } else {
96                            throw new NostationException();
97                    }
98            }
99            
100            public StationBean dumpAll() throws SQLException {
101                    
102                    String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0,aliases " +
103                                    "FROM trainstations WHERE enabled = true ORDER BY id";
104                    
105                  Connection conn = null;                  Connection conn = null;
106                  Statement stmt = null;                  Statement stmt = null;
107                  ResultSet res = null;                  ResultSet res = null;          
                 StationBean result;  
108    
109                    
110                  try {                  try {
111                          conn = DBConnection.getConnection();                          conn = DBConnection.getConnection();
112    
113                          stmt = conn.createStatement();                          stmt = conn.createStatement();
114                          res = stmt.executeQuery(SQL);                                    res = stmt.executeQuery(SQL);          
115                          res.next();                                                  
116                          result = convertSingleRow(res);                          // Does mostly the same as convertResultset()
117                            StationBean stations = new StationBean();
118                            while (res.next()) {
119                                    StationEntry entry = convertSingleRow(res);
120                                    
121                                    Array arr = res.getArray(10);
122                                    if (arr != null) {
123                                            String[] aliases = (String[]) arr.getArray();
124                                            entry.setAliases(aliases);
125                                    }
126                                    
127                                    stations.entries.add( entry );
128                                    
129                            }
130                            return stations;
131                            
132    
133                  } finally {                  } finally {
134                          if (res != null)                          if (res != null)
135                                  res.close();                                  res.close();
# Line 64  public class StationDAO { Line 138  public class StationDAO {
138                          if (conn != null)                          if (conn != null)
139                                  conn.close();                                  conn.close();
140                  }                  }
141                    
                 return result;  
142          }          }
143    
144          /*          /*
# Line 74  public class StationDAO { Line 147  public class StationDAO {
147           *     'select $2 ilike $1' language sql strict immutable;           *     'select $2 ilike $1' language sql strict immutable;
148           *     create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~);           *     create operator ~~~ (procedure = rlike, leftarg = text, rightarg = text, commutator = ~~);
149           */           */
150          public List<StationBean> getByName(String name) throws SQLException {          public StationBean getByName(final String name) throws SQLException {
151                  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 " +
152                  "FROM trainstations " +                  "FROM trainstations " +
153                  "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " +                  "WHERE (name ILIKE ? OR ? ~~~ ANY(aliases)) AND enabled = true " +
154                  "ORDER BY name ";                  "ORDER BY name ";
155    
156                    class NameSetter implements StatementParamSetter {
157                  List<StationBean> result;                          @Override
158                  Connection conn = null;                          public void setParams(PreparedStatement stmt) throws SQLException {
159                  PreparedStatement stmt = null;                                  stmt.setString(1, name + "%");
160                  ResultSet res = null;                                  stmt.setString(2, name + "%");                          
161                  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();  
162                  }                  }
163                  return result;                  
164                    return fetchStations(SQL, new NameSetter() );
165          }          }
166    
167          //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
168            // 1 degree latitude is ~ 111320 meters, since the distance between the horizonal lines is always the same
169            // 1 degree longitude is ~111320 meters at equator but gets shorter as we get closer to the poles.
170            // the "hack" with max 0.4 degrees latitude and 0.75 degrees longitude is only valid since we only service danish trains,
171          // in denmark 0.4dg latitude ~ 44km, 0.75dg longitude ~ 47km          // in denmark 0.4dg latitude ~ 44km, 0.75dg longitude ~ 47km
172    
173          // 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 114  public class StationDAO { Line 175  public class StationDAO {
175          // calculate the distance:          // calculate the distance:
176          //     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
177    
178          public List<StationBean> getByLocationWorker(double latitude, double longitude, boolean geolimit) throws SQLException {          public StationBean getByLocationWorker(final double latitude, final double longitude, final boolean geolimit) throws SQLException {
179                                    
180                  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 " : "";
181                                    
# Line 125  public class StationDAO { Line 186  public class StationDAO {
186                          "ORDER BY calcdist ASC " +                          "ORDER BY calcdist ASC " +
187                          "LIMIT " + LOCATION_LIMIT;                          "LIMIT " + LOCATION_LIMIT;
188    
   
189                                    
190                  List<StationBean> result;                  class LatlongSetter implements StatementParamSetter {
191                  Connection conn = null;                          @Override
192                  PreparedStatement stmt = null;                          public void setParams(PreparedStatement stmt) throws SQLException {
193                  ResultSet res = null;                                  stmt.setDouble(1, latitude);
194                  try {                                  stmt.setDouble(2, longitude);
195                          conn = DBConnection.getConnection();                                  if (geolimit == true) {
196                          stmt = conn.prepareStatement(SQL);                                          stmt.setDouble(3, latitude);
197                          stmt.setDouble(1, latitude);                                          stmt.setDouble(4, longitude);
198                          stmt.setDouble(2, longitude);                                  }                              
199                          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();  
200                  }                  }
201                  return result;                  
202                    return fetchStations(SQL, new LatlongSetter() );
203          }          }
204                    
205          public List<StationBean> getByLocation(double latitude, double longitude) throws SQLException {          public StationBean getByLocation(double latitude, double longitude) throws SQLException {
206                  List<StationBean> result = getByLocationWorker(latitude, longitude, true);                  StationBean result = getByLocationWorker(latitude, longitude, true);
207                                    
208                  if (result.size() < LOCATION_LIMIT) { //failover                  if (result.entries.size() < LOCATION_LIMIT) { //failover
209                          logger.info("getByLocation failover: " +latitude + "," + longitude);                          logger.info("getByLocation failover: " +latitude + "," + longitude);
210                                                    
211                          result = getByLocationWorker(latitude, longitude, false);                          result = getByLocationWorker(latitude, longitude, false);
# Line 168  public class StationDAO { Line 216  public class StationDAO {
216                    
217                    
218    
219          public List<StationBean> getByList(String list) throws SQLException {          public StationBean getByList(String list) throws SQLException {
220                  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 " +
221                  "FROM trainstations " +                  "FROM trainstations " +
222                  "WHERE id IN " + list + " AND enabled = true " +                  "WHERE id IN " + list + " AND enabled = true " +
223                  "ORDER BY name ";                  "ORDER BY name ";
224                    
225                    return fetchStations(SQL, new NullSetter() );
226            }
227            
228    
229                  Connection conn = null;          
230                  Statement stmt = null;          public StationEntry getSimpleByName(final String name) throws SQLException {
231                  ResultSet res = null;                  String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " +
232                  List<StationBean> result;                  "FROM trainstations " +
233                    "WHERE name = ?  AND enabled = true " +
234                    "LIMIT 1 ";
235    
236                  try {                  class NameSetter implements StatementParamSetter {
237                          conn = DBConnection.getConnection();                          @Override
238                          stmt = conn.createStatement();                          public void setParams(PreparedStatement stmt) throws SQLException {
239                          res = stmt.executeQuery(SQL);                                  stmt.setString(1, name );
240                          result = convertResultset(res);                          }                      
241                  } finally {                  }
242                          if (res != null)                  
243                                  res.close();                  StationBean stations = fetchStations(SQL, new NameSetter() );
244                          if (stmt != null)                  
245                                  stmt.close();                  if (stations.entries.size() == 1) {
246                          if (conn!= null)                          return stations.entries.get(0);
247                                  conn.close();                  } else {
248                            return null;
249                  }                  }
   
                 return result;  
   
250          }          }
251    
252            @Deprecated
253          public static String getStationName(int stationID) {          public static String getStationName(int stationID) {
254                  String station = "";                  String station = "";
255    
# Line 218  public class StationDAO { Line 272  public class StationDAO {
272    
273                  return station;                  return station;
274          }          }
275            
276          public int getIdByName(String name) throws SQLException {          
277            
278            @Deprecated
279            public int getIdByName(final String name) throws SQLException {
280                  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 " +
281                  "FROM trainstations " +                  "FROM trainstations " +
282                  "WHERE name = ?  AND enabled = true " +                  "WHERE name = ?  AND enabled = true " +
283                  "LIMIT 1 ";                  "LIMIT 1 ";
284    
285                  List<StationBean> result;                  class NameSetter implements StatementParamSetter {
286                  Connection conn = null;                          @Override
287                  PreparedStatement stmt = null;                          public void setParams(PreparedStatement stmt) throws SQLException {
288                  ResultSet res = null;                                  stmt.setString(1, name );
289                  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();  
290                  }                  }
291                    
292                  if (result.size() == 1) {                  StationBean stations = fetchStations(SQL, new NameSetter() );
293                          return result.get(0).getId();                  
294                    if (stations.entries.size() == 1) {
295                            return stations.entries.get(0).getId();
296                  } else {                  } else {
297                          return -1;                          return -1;
298                  }                  }

Legend:
Removed from v.929  
changed lines
  Added in v.1504

  ViewVC Help
Powered by ViewVC 1.1.20