]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/GetWikipediaFunction.java
Version 19.1, August 2018
[GpsPrune.git] / tim / prune / function / GetWikipediaFunction.java
1 package tim.prune.function;
2
3 import java.io.BufferedReader;
4 import java.io.InputStream;
5 import java.io.InputStreamReader;
6 import java.net.URL;
7 import java.util.ArrayList;
8
9 import javax.xml.parsers.SAXParser;
10 import javax.xml.parsers.SAXParserFactory;
11
12 import tim.prune.App;
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;
22
23 /**
24  * Function to load nearby point information from Wikipedia (and Wikimedia)
25  * according to the currently viewed area
26  */
27 public class GetWikipediaFunction extends GenericDownloaderFunction
28 {
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";
35
36
37         /**
38          * Constructor
39          * @param inApp App object
40          */
41         public GetWikipediaFunction(App inApp) {
42                 super(inApp);
43         }
44
45         /**
46          * @return name key
47          */
48         public String getNameKey() {
49                 return "function.getwikipedia";
50         }
51
52         /**
53          * @param inColNum index of column, 0 or 1
54          * @return key for this column
55          */
56         protected String getColumnKey(int inColNum)
57         {
58                 if (inColNum == 0) return "dialog.wikipedia.column.name";
59                 return "dialog.wikipedia.column.distance";
60         }
61
62
63         /**
64          * Run method to get the nearby points in a separate thread
65          */
66         public void run()
67         {
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();
72                 if (point == null)
73                 {
74                         double[] coords = _app.getViewport().getBounds();
75                         lat = (coords[0] + coords[2]) / 2.0;
76                         lon = (coords[1] + coords[3]) / 2.0;
77                 }
78                 else
79                 {
80                         lat = point.getLatitude().getDouble();
81                         lon = point.getLongitude().getDouble();
82                 }
83
84                 // Before we ask geonames online, let's get wikimedia galleries first
85                 searchWikimediaGalleries(lat, lon);
86
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");
93                 }
94                 // If still nothing then try english
95                 if (_trackListModel.isEmpty() && _errorMessage == null && !lang.equals("en")) {
96                         submitSearch(lat, lon, "en");
97                 }
98
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");
102                 }
103                 _statusLabel.setText(_errorMessage == null ? "" : _errorMessage);
104         }
105
106         /**
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
111          */
112         private void submitSearch(double inLat, double inLon, String inLang)
113         {
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;
122
123                 try
124                 {
125                         URL url = new URL(urlString);
126                         SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
127                         inStream = url.openStream();
128                         saxParser.parse(inStream, xmlHandler);
129                 }
130                 catch (Exception e) {
131                         _errorMessage = e.getClass().getName() + " - " + e.getMessage();
132                 }
133                 // Close stream and ignore errors
134                 try {
135                         inStream.close();
136                 } catch (Exception e) {}
137                 // Add track list to model
138                 ArrayList<SearchResult> trackList = xmlHandler.getTrackList();
139                 _trackListModel.addTracks(trackList, true);
140
141                 // Show error message if any
142                 if (_trackListModel.isEmpty())
143                 {
144                         String error = xmlHandler.getErrorMessage();
145                         if (error != null && !error.equals(""))
146                         {
147                                 _app.showErrorMessageNoLookup(getNameKey(), error);
148                                 _errorMessage = error;
149                         }
150                 }
151         }
152
153         /**
154          * Load the selected point(s)
155          */
156         protected void loadSelected()
157         {
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++)
163                 {
164                         int rowNum = rowNums[i];
165                         if (rowNum >= 0 && rowNum < _trackListModel.getRowCount())
166                         {
167                                 String lat = _trackListModel.getTrack(rowNum).getLatitude();
168                                 String lon = _trackListModel.getTrack(rowNum).getLongitude();
169                                 if (lat != null && lon != null)
170                                 {
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);
174                                 }
175                         }
176                 }
177                 // Close the dialog
178                 _cancelled = true;
179                 _dialog.dispose();
180         }
181
182         /**
183          * Search the local wikimedia index to see if there are any galleries nearby
184          * @param inLat latitude
185          * @param inLon longitude
186          */
187         private void searchWikimediaGalleries(double inLat, double inLon)
188         {
189                 BufferedReader reader = null;
190                 try
191                 {
192                         InputStream in = GetWikipediaFunction.class.getResourceAsStream("/tim/prune/function/search/wikimedia_galleries.txt");
193                         reader = new BufferedReader(new InputStreamReader(in));
194
195                         ArrayList<SearchResult> trackList = new ArrayList<SearchResult>();
196                         DataPoint herePoint = new DataPoint(new Latitude(inLat, Latitude.FORMAT_DEG), new Longitude(inLon, Longitude.FORMAT_DEG), null);
197                         // Loop through the file line by line, looking for nearby points
198                         String line = null;
199                         while ((line = reader.readLine()) != null)
200                         {
201                                 String[] lineComps = line.split("\t");
202                                 if (lineComps.length == 4)
203                                 {
204                                         DataPoint p = new DataPoint(new Latitude(lineComps[2]), new Longitude(lineComps[3]), null);
205                                         double distFromHere = Distance.convertRadiansToDistance(
206                                                 DataPoint.calculateRadiansBetween(p, herePoint), UnitSetLibrary.UNITS_KILOMETRES);
207                                         if (distFromHere < MAX_DISTANCE)
208                                         {
209                                                 SearchResult gallery = new SearchResult();
210                                                 gallery.setTrackName(I18nManager.getText("dialog.wikipedia.gallery") + ": " + lineComps[0]);
211                                                 gallery.setDescription(lineComps[1]);
212                                                 gallery.setLatitude(lineComps[2]);
213                                                 gallery.setLongitude(lineComps[3]);
214                                                 gallery.setWebUrl("https://commons.wikimedia.org/wiki/" + lineComps[0]);
215                                                 gallery.setLength(distFromHere * 1000.0); // convert from km to m
216                                                 trackList.add(gallery);
217                                         }
218                                 }
219                         }
220                         _trackListModel.addTracks(trackList, true);
221                 }
222                 catch (java.io.IOException e) {
223                         System.err.println("Exception trying to read wikimedia file : " + e.getMessage());
224                 }
225                 catch (NullPointerException e) {
226                         System.err.println("Couldn't find wikimedia file : " + e.getMessage());
227                 }
228                 finally
229                 {
230                         try {
231                                 reader.close();
232                         }
233                         catch (Exception e) {} // ignore
234                 }
235         }
236 }