1 package tim.prune.function;
3 import java.io.BufferedReader;
4 import java.io.InputStream;
5 import java.io.InputStreamReader;
7 import java.util.ArrayList;
9 import javax.xml.parsers.SAXParser;
10 import javax.xml.parsers.SAXParserFactory;
13 import tim.prune.I18nManager;
14 import tim.prune.data.DataPoint;
15 import tim.prune.data.Distance;
16 import tim.prune.data.Field;
17 import tim.prune.data.Latitude;
18 import tim.prune.data.Longitude;
19 import tim.prune.data.UnitSetLibrary;
20 import tim.prune.function.search.GenericDownloaderFunction;
21 import tim.prune.function.search.SearchResult;
24 * Function to load nearby point information from Wikipedia (and Wikimedia)
25 * according to the currently viewed area
27 public class GetWikipediaFunction extends GenericDownloaderFunction
29 /** Maximum number of results to get */
30 private static final int MAX_RESULTS = 20;
31 /** Maximum distance from point in km */
32 private static final int MAX_DISTANCE = 15;
33 /** Username to use for geonames queries */
34 private static final String GEONAMES_USERNAME = "gpsprune";
39 * @param inApp App object
41 public GetWikipediaFunction(App inApp) {
48 public String getNameKey() {
49 return "function.getwikipedia";
53 * @param inColNum index of column, 0 or 1
54 * @return key for this column
56 protected String getColumnKey(int inColNum)
58 if (inColNum == 0) return "dialog.wikipedia.column.name";
59 return "dialog.wikipedia.column.distance";
64 * Run method to get the nearby points in a separate thread
68 _statusLabel.setText(I18nManager.getText("confirm.running"));
69 // Get coordinates from current point (if any) or from centre of screen
70 double lat = 0.0, lon = 0.0;
71 DataPoint point = _app.getTrackInfo().getCurrentPoint();
74 double[] coords = _app.getViewport().getBounds();
75 lat = (coords[0] + coords[2]) / 2.0;
76 lon = (coords[1] + coords[3]) / 2.0;
80 lat = point.getLatitude().getDouble();
81 lon = point.getLongitude().getDouble();
84 // Before we ask geonames online, let's get wikimedia galleries first
85 searchWikimediaGalleries(lat, lon);
87 // For geonames, firstly try the local language
88 String lang = I18nManager.getText("wikipedia.lang");
89 submitSearch(lat, lon, lang);
90 // If we didn't get anything, try a secondary language
91 if (_trackListModel.isEmpty() && _errorMessage == null && lang.equals("als")) {
92 submitSearch(lat, lon, "de");
94 // If still nothing then try english
95 if (_trackListModel.isEmpty() && _errorMessage == null && !lang.equals("en")) {
96 submitSearch(lat, lon, "en");
99 // Set status label according to error or "none found", leave blank if ok
100 if (_errorMessage == null && _trackListModel.isEmpty()) {
101 _errorMessage = I18nManager.getText("dialog.wikipedia.nonefound");
103 _statusLabel.setText(_errorMessage == null ? "" : _errorMessage);
107 * Submit the search for the given parameters
108 * @param inLat latitude
109 * @param inLon longitude
110 * @param inLang language code to use, such as en or de
112 private void submitSearch(double inLat, double inLon, String inLang)
114 // Example http://api.geonames.org/findNearbyWikipedia?lat=47&lng=9
115 String urlString = "http://api.geonames.org/findNearbyWikipedia?lat=" +
116 inLat + "&lng=" + inLon + "&maxRows=" + MAX_RESULTS
117 + "&radius=" + MAX_DISTANCE + "&lang=" + inLang
118 + "&username=" + GEONAMES_USERNAME;
119 // Parse the returned XML with a special handler
120 GetWikipediaXmlHandler xmlHandler = new GetWikipediaXmlHandler();
121 InputStream inStream = null;
125 URL url = new URL(urlString);
126 SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
127 inStream = url.openStream();
128 saxParser.parse(inStream, xmlHandler);
130 catch (Exception e) {
131 _errorMessage = e.getClass().getName() + " - " + e.getMessage();
133 // Close stream and ignore errors
136 } catch (Exception e) {}
137 // Add track list to model
138 ArrayList<SearchResult> trackList = xmlHandler.getTrackList();
139 _trackListModel.addTracks(trackList, true);
141 // Show error message if any
142 if (_trackListModel.isEmpty())
144 String error = xmlHandler.getErrorMessage();
145 if (error != null && !error.equals(""))
147 _app.showErrorMessageNoLookup(getNameKey(), error);
148 _errorMessage = error;
154 * Load the selected point(s)
156 protected void loadSelected()
158 // Find the rows selected in the table and get the corresponding coords
159 int numSelected = _trackTable.getSelectedRowCount();
160 if (numSelected < 1) return;
161 int[] rowNums = _trackTable.getSelectedRows();
162 for (int i=0; i<numSelected; i++)
164 int rowNum = rowNums[i];
165 if (rowNum >= 0 && rowNum < _trackListModel.getRowCount())
167 String lat = _trackListModel.getTrack(rowNum).getLatitude();
168 String lon = _trackListModel.getTrack(rowNum).getLongitude();
169 if (lat != null && lon != null)
171 DataPoint point = new DataPoint(new Latitude(lat), new Longitude(lon), null);
172 point.setFieldValue(Field.WAYPT_NAME, _trackListModel.getTrack(rowNum).getTrackName(), false);
173 _app.createPoint(point);
183 * Search the local wikimedia index to see if there are any galleries nearby
184 * @param inLat latitude
185 * @param inLon longitude
187 private void searchWikimediaGalleries(double inLat, double inLon)
189 BufferedReader reader = null;
192 InputStream in = GetWikipediaFunction.class.getResourceAsStream("/tim/prune/function/search/wikimedia_galleries.txt");
193 reader = new BufferedReader(new InputStreamReader(in));
196 ArrayList<SearchResult> trackList = new ArrayList<SearchResult>();
197 DataPoint herePoint = new DataPoint(new Latitude(inLat, Latitude.FORMAT_DEG), new Longitude(inLon, Longitude.FORMAT_DEG), null);
198 // Loop through the file line by line, looking for nearby points
200 while ((line = reader.readLine()) != null)
202 String[] lineComps = line.split("\t");
203 if (lineComps.length == 4)
205 DataPoint p = new DataPoint(new Latitude(lineComps[2]), new Longitude(lineComps[3]), null);
206 double distFromHere = Distance.convertRadiansToDistance(
207 DataPoint.calculateRadiansBetween(p, herePoint), UnitSetLibrary.UNITS_KILOMETRES);
208 if (distFromHere < MAX_DISTANCE)
210 SearchResult gallery = new SearchResult();
211 gallery.setTrackName(I18nManager.getText("dialog.wikipedia.gallery") + ": " + lineComps[0]);
212 gallery.setDescription(lineComps[1]);
213 gallery.setLatitude(lineComps[2]);
214 gallery.setLongitude(lineComps[3]);
215 gallery.setWebUrl("https://commons.wikimedia.org/wiki/" + lineComps[0]);
216 gallery.setLength(distFromHere * 1000.0); // convert from km to m
217 trackList.add(gallery);
221 _trackListModel.addTracks(trackList, true);
224 catch (java.io.IOException e) {
225 System.err.println("Exception trying to read wikimedia file : " + e.getMessage());
227 catch (NullPointerException e) {
228 System.err.println("Couldn't find wikimedia file : " + e.getMessage());
235 catch (Exception e) {} // ignore