/[projects]/android/TrainInfo/src/dk/thoerup/traininfo/provider/OfflineStationProvider.java
ViewVC logotype

Diff of /android/TrainInfo/src/dk/thoerup/traininfo/provider/OfflineStationProvider.java

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

revision 1551 by torben, Thu Jul 7 20:45:17 2011 UTC revision 1795 by torben, Wed Apr 11 17:45:34 2012 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfo.provider;  package dk.thoerup.traininfo.provider;
2    
 import java.io.EOFException;  
3  import java.io.File;  import java.io.File;
4  import java.io.FileInputStream;  import java.io.FileInputStream;
5  import java.io.FileOutputStream;  import java.io.FileOutputStream;
6    import java.io.IOException;
7  import java.io.ObjectInputStream;  import java.io.ObjectInputStream;
8  import java.io.ObjectOutputStream;  import java.io.ObjectOutputStream;
9  import java.util.ArrayList;  import java.net.URLEncoder;
10  import java.util.Collections;  import java.util.Collections;
11  import java.util.Comparator;  import java.util.Comparator;
12    import java.util.LinkedList;
13    
14  import org.simpleframework.xml.Serializer;  import org.simpleframework.xml.Serializer;
15  import org.simpleframework.xml.core.Persister;  import org.simpleframework.xml.core.Persister;
# Line 19  import android.util.Log; Line 20  import android.util.Log;
20  import dk.thoerup.android.traininfo.common.StationBean;  import dk.thoerup.android.traininfo.common.StationBean;
21  import dk.thoerup.android.traininfo.common.StationEntry;  import dk.thoerup.android.traininfo.common.StationEntry;
22  import dk.thoerup.genericjavautils.HttpUtil;  import dk.thoerup.genericjavautils.HttpUtil;
23    import dk.thoerup.traininfo.util.DownloadUtil;
24  import dk.thoerup.traininfo.util.IntSet;  import dk.thoerup.traininfo.util.IntSet;
25  import dk.thoerup.traininfo.util.XmlUtil;  import dk.thoerup.traininfo.util.XmlUtil;
26    
# Line 26  public class OfflineStationProvider impl Line 28  public class OfflineStationProvider impl
28                    
29          StationBean stations = new StationBean();          StationBean stations = new StationBean();
30    
31            boolean statsByNameSend = false;
32    
33            public boolean hasStations() {
34                    return (stations != null && stations.entries.size() > 0);
35            }
36            
37    
38          public boolean loadStations(Context context) throws Exception {          public boolean loadStations(Context context) throws Exception {
39                  stations.entries.clear(); //TODO: remove                  long start = System.currentTimeMillis();
40                    
41                    StationBean tmpStations = new StationBean();
42                                    
43                  File parent = context.getFilesDir();                  File parent = context.getFilesDir();
44                  File stationsFile = new File(parent, "stations.bin");                  File stationsFile = new File(parent, "stations.bin");
# Line 46  public class OfflineStationProvider impl Line 56  public class OfflineStationProvider impl
56                  stations = serializer.read(StationBean.class,  new String(data, "ISO-8859-1") );*/                  stations = serializer.read(StationBean.class,  new String(data, "ISO-8859-1") );*/
57                                    
58                                    
59                  try {  
60                          ObjectInputStream in = new ObjectInputStream( new FileInputStream(stationsFile) );                  ObjectInputStream in = new ObjectInputStream( new FileInputStream(stationsFile) );
61                          Object o;  
62                          while ( (o=in.readObject()) != null ) {                  int length = in.readInt(); // first field is the length
63                                  stations.entries.add( (StationEntry) o);                  
64                          }                  for (int i=0; i<length; i++) {                          
65                          in.close();                          StationEntry entry = (StationEntry) in.readObject();
66                  } catch (EOFException e) {                          updateSearchStrings(entry);
67                          //do nothing;                          tmpStations.entries.add( entry );
68                  }                  }
69                                    
70                  Log.e("OFFLINE", "loaded" + stations.entries.size());                  in.close();
71    
72                    stations = tmpStations; // når indlæsningen er ok skifter vi over
73                    
74                    Log.e("OFFLINE", "loaded" + tmpStations.entries.size());
75                    logElapsedTime(start, "loadStations");
76                                    
77                  return true;                  return true;
78          }                }
79            
80            public void updateSearchStrings(StationEntry entry) {          
81                    entry.nameLower = entry.getName().toLowerCase();
82                    entry.nameInternational = entry.nameLower.replace("æ", "ae").replace("ø", "oe").replace("å", "aa");
83            }
84                    
85          public void downloadStations(Context context) throws Exception {          public void downloadStations(Context context) throws Exception {
86                  File parent = context.getFilesDir();                  File parent = context.getFilesDir();
87                  File stationsFile = new File(parent, "stations.bin");                  File stationsFile = new File(parent, "stations.bin");
88    
89                                    long start = System.currentTimeMillis();
90                  byte data[] = HttpUtil.getContent(XmlUtil.SERVICE_BASE + "/LocateStations?dump=1", 5000);                  byte data[] = HttpUtil.getContent(XmlUtil.SERVICE_BASE + "/LocateStations?dump=1", 5000);
91                  Serializer serializer = new Persister();                  logElapsedTime(start, "download XML");
92                  stations = serializer.read(StationBean.class,  new String(data, "ISO-8859-1") );                  
93                    
94                    Serializer serializer = new Persister();                
95                    
96                    start = System.currentTimeMillis();
97                    StationBean tmpStations = serializer.read(StationBean.class,  new String(data, "ISO-8859-1") );
98                    logElapsedTime(start, "parse XML");
99                                    
100                                    
101                  ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(stationsFile) );                  ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(stationsFile) );
102                  Log.e("OFFLINE", "data size" + data.length);                  Log.e("OFFLINE", "data size" + data.length);
103                                    
104                  for (StationEntry entry : stations.entries) {                  out.writeInt( tmpStations.entries.size() ); //start with writing the length of the dataset
105                    
106                    for (StationEntry entry : tmpStations.entries) {
107                            updateSearchStrings( entry ); //prepare name fields for byName search
108                          out.writeObject(entry);                          out.writeObject(entry);
109                  }                  }
110                                    
111                  out.close();                              out.close();
112                    
113                    stations = tmpStations; // når alt er ok skifter vi over til ny udgave
114          }          }
115                    
116                    
# Line 88  public class OfflineStationProvider impl Line 119  public class OfflineStationProvider impl
119          public void purgeOldEntries() {          public void purgeOldEntries() {
120          }          }
121    
122            Comparator<StationEntry> distanceComparator = new Comparator<StationEntry>() {
123                    @Override
124                    public int compare(StationEntry object1, StationEntry object2) {
125                            if (object1.getCalcdist() == object2.getCalcdist())                                    
126                                    return 0;
127                            
128                            if (object1.getCalcdist() > object2.getCalcdist())
129                                    return 1;
130                            else
131                                    return -1;
132                    }              
133            };
134                    
135          @Override          @Override
136          public StationBean lookupStationsByLocation(Location location) {          public StationBean lookupStationsByLocation(Location location) {
137                                    
138                    statsByLocation(location);
139                    
140                    long start = System.currentTimeMillis();
141                  Location tmpLoc = new Location("GPS");                  Location tmpLoc = new Location("GPS");
142                                    
143                  ArrayList<StationEntry> entries = new ArrayList<StationEntry>() ;                  LinkedList<StationEntry> entries = new LinkedList<StationEntry>() ;
144                                    
145                  for (StationEntry entry : stations.entries) {                  for (StationEntry entry : stations.entries) {
146                          tmpLoc.setLatitude(entry.getLatitude());                          tmpLoc.setLatitude(entry.getLatitude());
147                          tmpLoc.setLongitude(entry.getLongitude());                          tmpLoc.setLongitude(entry.getLongitude());
148                                                    
149                          entry.setCalcdist( (int) location.distanceTo(tmpLoc) );                          int distance = (int) location.distanceTo(tmpLoc);
                         entries.add(entry);  
150                                                    
151                  }                          if (entries.size() <8 || entries.getLast().getCalcdist() > distance) {
152                                                    entry.setCalcdist(distance);
                 Collections.sort( entries, new Comparator<StationEntry>() {  
                         @Override  
                         public int compare(StationEntry object1, StationEntry object2) {  
                                 if (object1.getCalcdist() == object2.getCalcdist())                                      
                                         return 0;  
153                                                                    
154                                  if (object1.getCalcdist() > object2.getCalcdist())                                  if (entries.size() == 8)
155                                          return 1;                                          entries.removeLast();
156                                  else                                  
157                                          return -1;                                  entries.addLast(entry);
158                          }                                  
159                                                            Collections.sort( entries, distanceComparator);
160                  });                          }                      
161                    }
162                                    
163                    logElapsedTime(start, "location_stage1");
164                                    
165                    Collections.sort( entries, distanceComparator);
166                                    
167                  StationBean tmpStations = new StationBean();                  StationBean tmpStations = new StationBean();
168                  for (int i = 0; i<8; i++) {                  for (int i = 0; i<8 && i<entries.size(); i++) {
169                          tmpStations.entries.add( entries.get(i) );                          tmpStations.entries.add( entries.get(i) );
170                  }                  }
171                                    
172                    logElapsedTime(start, "location");
173                  return tmpStations;                  return tmpStations;
174          }          }
175            
176            private void logElapsedTime(long start, String method) {
177                    long now = System.currentTimeMillis();
178                    
179                    Log.i("TrainInfo", "Search by " + method + " elapsed " + (now-start) );
180            }
181    
182          @Override          @Override
183          public StationBean lookupStationsByName(String name) {          public StationBean lookupStationsByName(String name) {
184            
185                    statsByName(name);      
186                    
187                    long start = System.currentTimeMillis();
188                                    
189                  name = name.toLowerCase();                  name = name.toLowerCase();
190                  StationBean tmpStations = new StationBean();                  StationBean tmpStations = new StationBean();
191                  for (StationEntry entry : stations.entries) {                  for (StationEntry entry : stations.entries) {
192                          if (entry.getName().toLowerCase().startsWith(name) ) {                          if (entry.nameLower.startsWith(name) || entry.nameInternational.startsWith(name) || aliasNameMatch(name,entry) ) {
193                                  tmpStations.entries.add(entry);                                  tmpStations.entries.add(entry);
194                          }                          }
195                  }                  }
196                                                                    logElapsedTime(start, "name");                          
197                  return tmpStations;                  return tmpStations;
198          }          }
199            
200            private boolean aliasNameMatch(String name, StationEntry station) {
201                    for(String alias : station.getAliases()) {
202                            if (alias.startsWith(name)) {
203                                    return true;
204                            }
205                    }
206                    return false;
207            }
208    
209          @Override          @Override
210          public StationBean lookupStationsByIds(String ids) {          public StationBean lookupStationsByIds(String ids) {
211                    statsByIds(ids);
212                    
213                  IntSet idset = new IntSet();                  IntSet idset = new IntSet();
214                  idset.fromString(ids);                  idset.fromString(ids);
215                                    
# Line 155  public class OfflineStationProvider impl Line 220  public class OfflineStationProvider impl
220                          }                          }
221                  }                  }
222                                    
223                    return tmpStations;
224            }
225            
226    
227            private void statsByLocation(Location location) {
228                    double lat = XmlStationProvider.roundToPlaces(location.getLatitude(), 4);
229                    double lng = XmlStationProvider.roundToPlaces(location.getLongitude(), 4);
230                    
231                    final String url = XmlUtil.SERVICE_BASE + "/LocateStations?latitude=" + lat + "&longitude=" + lng + "&dummy=1";
232                    Log.i("url", url);
233                    urlSender(url);
234            }
235            
236            private void statsByName(String name) {
237                    if (statsByNameSend == true) {
238                            return;
239                    }
240                    statsByNameSend = true;
241                                    
242                    try {
243                            name = URLEncoder.encode(name, "ISO8859-1");    
244                    } catch (Exception e) {
245                            Log.e("lookupStations", "Encoding failed", e);//if encoding fails use original and hope for the best
246                    }
247                                    
248                  return tmpStations;                  String url = XmlUtil.SERVICE_BASE + "/LocateStations?name=" + name + "&dummy=1";
249                    Log.i("url", url);
250                    urlSender(url);
251          }          }
252            
253            private void statsByIds(String ids) {  
254                    final String url = XmlUtil.SERVICE_BASE + "/LocateStations?list=" + ids + "&dummy=1";
255                    Log.i("url", url);
256                    urlSender(url);
257            }
258            
259            private void urlSender(final String url) {
260                    Thread t = new Thread(new Runnable() {
261    
262                            @Override
263                            public void run() {
264                                    try {
265                                            DownloadUtil.getContentString(url, 15000, "ISO-8859-1");
266                                    } catch (IOException e) {
267                                            Log.e("TrainInfo", "stats failed");
268                                    }                              
269                            }                      
270                    });
271                    t.start();
272            }
273            
274    
275  }  }

Legend:
Removed from v.1551  
changed lines
  Added in v.1795

  ViewVC Help
Powered by ViewVC 1.1.20