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

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

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

android/TrainInfoService/src/dk/thoerup/traininfoservice/StationDAO.java revision 588 by torben, Mon Feb 8 19:12:15 2010 UTC android/TrainInfoServiceGoogle/src/dk/thoerup/traininfoservice/StationDAO.java revision 1106 by torben, Wed Sep 22 22:46:26 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice;  package dk.thoerup.traininfoservice;
2    
3  import java.sql.Connection;  import java.io.IOException;
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
4  import java.util.ArrayList;  import java.util.ArrayList;
5    import java.util.Collections;
6    import java.util.Comparator;
7    import java.util.Iterator;
8  import java.util.List;  import java.util.List;
9    import java.util.logging.Logger;
10    
11    import javax.jdo.PersistenceManager;
12    import javax.jdo.Query;
13    
14    import dk.thoerup.android.traininfo.common.StationBean;
15    import dk.thoerup.android.traininfo.common.StationBean.StationEntry;
16    import dk.thoerup.traininfoservice.geo.Geo;
17    import dk.thoerup.traininfoservice.jdo.JdoStationBean;
18    import dk.thoerup.traininfoservice.jdo.PMF;
19    
20  public class StationDAO {  public class StationDAO {
21          private StationBean convertSingleRow(ResultSet res) throws SQLException {          final static int LOCATION_LIMIT = 8;
22                  StationBean station = new StationBean();          static final Logger logger = Logger.getLogger(StationDAO.class.getName());
23                    
24                  station.setId( res.getInt(1) );  
25                  station.setName( res.getString(2) );          public StationEntry getById(int id)  {
26                  station.setLatitude( res.getDouble(3) );  
27                  station.setLongitude( res.getDouble(4) );                  PersistenceManager pm = null;
                 station.setRegional( res.getString(5) );  
                 station.setStrain( res.getString(6) );  
                 station.setMetro( res.getString(7) );  
                 station.setAddress( res.getString(8) );  
                 station.setCalcdist( (int)res.getDouble(9) );  
28                                    
29                  return station;                  try {
30          }                          pm = PMF.get().getPersistenceManager();
31                                    JdoStationBean bean =pm.getObjectById(JdoStationBean.class, new Integer(id) );
32          private List<StationBean> convertResultset(ResultSet res) throws SQLException {                          return bean.toStationEntry();
33                  List<StationBean> stations = new ArrayList<StationBean>();                  } finally {
34                  while (res.next()) {                          pm.close();
                         stations.add( convertSingleRow(res) );  
35                  }                  }
36                  return stations;          }
37    
38            /* damn that JDO sucks so we to the filtering in java-code */
39            public StationBean getByName(String searchname) {
40                    PersistenceManager pm = null;
41                                    
42                    try {
43                            pm = PMF.get().getPersistenceManager();
44                            
45                            
46                            
47                            Query q = pm.newQuery(JdoStationBean.class);
48                            q.setOrdering("name");                  
49                            List<JdoStationBean> beanList = (List<JdoStationBean>) q.execute();
50                            
51                            StationBean stationBean = new StationBean();
52                            
53                            searchname = searchname.toLowerCase();
54                            for(JdoStationBean bean : beanList) {
55                                    if (bean.getName().toLowerCase().startsWith(searchname)) {
56                                            stationBean.entries.add( bean.toStationEntry() );
57                                    } else {
58                                            for (String alias : bean.aliases ) {
59                                                    if (alias.toLowerCase().startsWith(searchname)) {
60                                                            stationBean.entries.add( bean.toStationEntry() );
61                                                    }
62                                            }
63                                    }
64                            }
65    
66                            return stationBean;                    
67                    } finally {
68                            pm.close();
69                    }
70          }          }
71                    
72    
73            //String limitExpression = (geolimit == true) ? "AND abs(latitude-?)<0.4 AND abs(longitude-?)<0.75 " : "";
74            public List<JdoStationBean> getByLocationList(double latitude, double longitude, boolean geolimit)  {
75                    
76          public StationBean getById(int id) throws SQLException {                  PersistenceManager pm = null;
77                  String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro,address,0.0 " +                  final double LAT = 0.4;
78                        "FROM trainstations WHERE id=" + id + " AND enabled=true";                  final double LNG = 0.75;
                   
                 Connection conn = null;  
                 StationBean result;  
79                                    
80                  try {                  try {
81                          conn = DBConnection.getConnection();                          pm = PMF.get().getPersistenceManager();
82                                            Query q = pm.newQuery(JdoStationBean.class);
83                          Statement stmt = conn.createStatement();                          
84                          ResultSet res = stmt.executeQuery(SQL);                                  
85                          res.next();                          
86                          result = convertSingleRow(res);                          if (geolimit == true) {
87                                    double minLat = latitude - LAT;
88                                    double maxLat = latitude + LAT;
89                                    
90                                    //DAMN JDO implementation only allows us to compare on one parameter
91    
92                                    String filter = String.format("latitude > %f && latitude < %f", minLat, maxLat);
93                                    
94                                    q.setFilter( filter );
95                            }
96                            
97                            List<JdoStationBean> beanList = (List<JdoStationBean>) q.execute();                    
98                            
99                            logger.info("beanList size " + beanList.size());
100                            
101                            return beanList;
102                  } finally {                  } finally {
103                          if (conn != null)                          pm.close();
                                 conn.close();  
104                  }                  }
105            }
106    
107    
108            public StationBean getByLocation(double latitude, double longitude)  {
109                                    
110                  return result;                  List<JdoStationBean> beanList = getByLocationList(latitude,longitude,true);
111                    
112                    if (beanList.size() < LOCATION_LIMIT ) {
113                            logger.info("getByLocation failover: " +latitude + "," + longitude);
114                            beanList = getByLocationList(latitude,longitude, false);
115                    }
116    
117                    StationBean stationBean = new StationBean();                    
118    
119    
120                    Geo location = new Geo(latitude,longitude);
121                    for(JdoStationBean bean : beanList) {
122                            double meter = Geo.distanceKM( location, new Geo(bean.getLatitude(), bean.getLongitude() )) * 1000.0;
123    
124                            bean.distance = (int) meter;
125                    }
126    
127    
128                    Collections.sort(beanList, new Comparator<JdoStationBean>() {
129                            @Override
130                            public int compare(JdoStationBean o1, JdoStationBean o2) {
131                                    if (o1.distance < o2.distance) {
132                                            return -1;
133                                    } else if (o1.distance > o2.distance) {
134                                            return 1;
135                                    } else {
136                                            return 0;
137                                    }
138                            }
139                    });
140    
141                    for (int i=0; i<LOCATION_LIMIT && i<beanList.size(); i++) {
142                            stationBean.entries.add( beanList.get(i).toStationEntry() );
143                    }
144    
145                    return stationBean;                    
146          }          }
147                    
           
         public List<StationBean> getByName(String name) throws SQLException {  
                 String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address, 0.0 " +  
                 "FROM trainstations " +  
                 "WHERE name ILIKE ? AND enabled = true " +  
                 "ORDER BY name ";  
148    
149            public StationBean getByList(String list)  {
150                    PersistenceManager pm = null;
151                                    
                 List<StationBean> result;  
                 Connection conn = null;  
152                  try {                  try {
153                          conn = DBConnection.getConnection();                          String parts[] = list.split(",");
                         PreparedStatement stmt = conn.prepareStatement(SQL);  
154                                                    
155                          stmt.setString(1, name + "%");                          StringBuilder filter = new StringBuilder();
156                                                    
157                          ResultSet rs = stmt.executeQuery();                          for(String part : parts)  {
158                          result = convertResultset(rs);                                  if (filter.length() > 0) {
159                                            filter.append( " || " );
160                                    }
161                                    filter.append("id == ").append(part);
162                            }                      
163                                                    
164                            //String filter = "id == 10 || id == 82"; //TODO: build filter
165                            
166                            pm = PMF.get().getPersistenceManager();
167                            Query q = pm.newQuery(JdoStationBean.class);
168                            q.setFilter( filter.toString() );
169                            q.setOrdering("name");
170                            
171                            List<JdoStationBean> beanList = (List<JdoStationBean>) q.execute();
172                            
173                            StationBean stationBean = new StationBean();
174                            
175                            for(JdoStationBean bean : beanList) {
176                                    stationBean.entries.add( bean.toStationEntry() );
177                            }
178    
179                            return stationBean;                    
180                  } finally {                  } finally {
181                          if (conn != null)                          pm.close();
                                 conn.close();  
182                  }                  }
183                  return result;  
184          }          }
185            
186          public List<StationBean> getByLocation(double latitude, double longitude) throws SQLException {  
187                  String SQL = "SELECT * FROM ( "+          public int getIdByName(String name)  {
188                  "               SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, stationcode_metro, address," +                  
189                  "                     earth_distance( ll_to_earth(latitude,longitude), ll_to_earth(?,?))::int AS calcdist " +                  List<JdoStationBean> beanList = null;
190                  "               FROM trainstations " +                  
191                  "               WHERE enabled = true " +                  PersistenceManager pm = null;
192                  "       ) AS trainstations2 " +                  
                 "ORDER BY calcdist ASC " +  
                 "LIMIT 4 ";  
                 List<StationBean> result;  
                 Connection conn = null;  
193                  try {                  try {
194                          conn = DBConnection.getConnection();                          
195                          PreparedStatement stmt = conn.prepareStatement(SQL);                          String filter = " name == '" + name + "'";
196                          stmt.setDouble(1, latitude);                          
197                          stmt.setDouble(2, longitude);                          pm = PMF.get().getPersistenceManager();
198                          ResultSet rs = stmt.executeQuery();                          Query q = pm.newQuery(JdoStationBean.class);
199                          result = convertResultset(rs);                          q.setFilter(filter);
200                            
201                            beanList = (List<JdoStationBean>) q.execute();
202                            
203                            StationBean stationBean = new StationBean();
204                            
205                            for(JdoStationBean bean : beanList) {
206                                    stationBean.entries.add( bean.toStationEntry() );
207                            }
208                                                    
209                  } finally {                  } finally {
210                          if (conn != null)                          pm.close();
211                                  conn.close();                  }
212    
213                    if ( beanList != null && beanList.size()  == 1) {
214                            return (int) beanList.get(0).getId();
215                    } else {
216                            return -1;
217                  }                  }
                 return result;  
218          }          }
219                    
220           public List<StationBean> getByList(String list) throws SQLException {          @SuppressWarnings("unchecked")
221                          String SQL = "SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog,stationcode_metro, address,0.0 " +          public int saveStations(StationBean stationBean) throws IOException {
222                          "FROM trainstations " +                  PersistenceManager pm = null;
223                          "WHERE id IN " + list + " AND enabled = true " +                  
224                          "ORDER BY name ";                  try {
225                            pm = PMF.get().getPersistenceManager();
226                                                    
227                          Connection conn = null;                          List oldEntries = (List) pm.newQuery(JdoStationBean.class).execute();
228                          List<StationBean> result;                          pm.deletePersistentAll(oldEntries);
229                                                    
230                          try {                          List<JdoStationBean> jdoList = new ArrayList<JdoStationBean>();
231                                  conn = DBConnection.getConnection();                          for (StationEntry station : stationBean.entries) {
232                                  Statement stmt = conn.createStatement();                                  JdoStationBean jdoBean = JdoStationBean.fromStationEntry(station);
233                                  ResultSet res = stmt.executeQuery(SQL);                                  
234                                  result = convertResultset(res);                                  jdoList.add(jdoBean);
235                          } finally {                                  
                                 if (conn!= null)  
                                         conn.close();  
236                          }                          }
237                            pm.makePersistentAll(jdoList);
238                                                    
239                          return result;                          return jdoList.size();
240                                                    
241           }                  } finally {
242                                    pm.close();
243                    }
244            }
245            
246  }  }

Legend:
Removed from v.588  
changed lines
  Added in v.1106

  ViewVC Help
Powered by ViewVC 1.1.20