source: josm/trunk/src/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmTask.java@ 14219

Last change on this file since 14219 was 14219, checked in by Don-vip, 6 years ago

fix #16695 - display remark from Overpass API when a download returns no data

  • Property svn:eol-style set to native
File size: 21.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions.downloadtasks;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.IOException;
7import java.net.URL;
8import java.util.ArrayList;
9import java.util.Arrays;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.Objects;
14import java.util.Set;
15import java.util.concurrent.Future;
16import java.util.regex.Matcher;
17import java.util.regex.Pattern;
18import java.util.stream.Stream;
19
20import org.openstreetmap.josm.data.Bounds;
21import org.openstreetmap.josm.data.DataSource;
22import org.openstreetmap.josm.data.ProjectionBounds;
23import org.openstreetmap.josm.data.ViewportData;
24import org.openstreetmap.josm.data.coor.LatLon;
25import org.openstreetmap.josm.data.osm.DataSet;
26import org.openstreetmap.josm.data.osm.OsmPrimitive;
27import org.openstreetmap.josm.data.osm.Relation;
28import org.openstreetmap.josm.data.osm.Way;
29import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
30import org.openstreetmap.josm.gui.MainApplication;
31import org.openstreetmap.josm.gui.MapFrame;
32import org.openstreetmap.josm.gui.PleaseWaitRunnable;
33import org.openstreetmap.josm.gui.io.UpdatePrimitivesTask;
34import org.openstreetmap.josm.gui.layer.OsmDataLayer;
35import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
36import org.openstreetmap.josm.gui.progress.ProgressMonitor;
37import org.openstreetmap.josm.io.BoundingBoxDownloader;
38import org.openstreetmap.josm.io.OsmServerLocationReader;
39import org.openstreetmap.josm.io.OsmServerLocationReader.OsmUrlPattern;
40import org.openstreetmap.josm.io.OsmServerReader;
41import org.openstreetmap.josm.io.OsmTransferCanceledException;
42import org.openstreetmap.josm.io.OsmTransferException;
43import org.openstreetmap.josm.tools.Logging;
44import org.openstreetmap.josm.tools.Utils;
45import org.xml.sax.SAXException;
46
47/**
48 * Open the download dialog and download the data.
49 * Run in the worker thread.
50 */
51public class DownloadOsmTask extends AbstractDownloadTask<DataSet> {
52
53 protected Bounds currentBounds;
54 protected DownloadTask downloadTask;
55
56 protected String newLayerName;
57
58 /** This allows subclasses to ignore this warning */
59 protected boolean warnAboutEmptyArea = true;
60
61 @Override
62 public String[] getPatterns() {
63 if (this.getClass() == DownloadOsmTask.class) {
64 return Arrays.stream(OsmUrlPattern.values()).map(OsmUrlPattern::pattern).toArray(String[]::new);
65 } else {
66 return super.getPatterns();
67 }
68 }
69
70 @Override
71 public String getTitle() {
72 if (this.getClass() == DownloadOsmTask.class) {
73 return tr("Download OSM");
74 } else {
75 return super.getTitle();
76 }
77 }
78
79 /**
80 * Asynchronously launches the download task for a given bounding box.
81 * @param newLayer true, if the data is to be downloaded into a new layer. If false, the task
82 * selects one of the existing layers as download layer, preferably the active layer.
83 *
84 * @param downloadArea the area to download
85 * @param progressMonitor the progressMonitor
86 * @return the future representing the asynchronous task
87 * @deprecated Use {@link #download(DownloadParams, Bounds, ProgressMonitor)}
88 */
89 @Deprecated
90 public Future<?> download(boolean newLayer, Bounds downloadArea, ProgressMonitor progressMonitor) {
91 return download(new BoundingBoxDownloader(downloadArea),
92 new DownloadParams().withNewLayer(newLayer), downloadArea, progressMonitor);
93 }
94
95 @Override
96 public Future<?> download(DownloadParams settings, Bounds downloadArea, ProgressMonitor progressMonitor) {
97 return download(new BoundingBoxDownloader(downloadArea), settings, downloadArea, progressMonitor);
98 }
99
100 /**
101 * Asynchronously launches the download task for a given bounding box.
102 *
103 * @param reader the reader used to parse OSM data (see {@link OsmServerReader#parseOsm})
104 * @param newLayer newLayer true, if the data is to be downloaded into a new layer. If false, the task
105 * selects one of the existing layers as download layer, preferably the active layer.
106 * @param downloadArea the area to download
107 * @param progressMonitor the progressMonitor
108 * @return the future representing the asynchronous task
109 * @deprecated Use {@link #download(OsmServerReader, DownloadParams, Bounds, ProgressMonitor)}
110 */
111 @Deprecated
112 public Future<?> download(OsmServerReader reader, boolean newLayer, Bounds downloadArea, ProgressMonitor progressMonitor) {
113 return download(new DownloadTask(new DownloadParams().withNewLayer(newLayer), reader, progressMonitor, zoomAfterDownload),
114 downloadArea);
115 }
116
117 /**
118 * Asynchronously launches the download task for a given bounding box.
119 *
120 * Set <code>progressMonitor</code> to null, if the task should create, open, and close a progress monitor.
121 * Set progressMonitor to {@link NullProgressMonitor#INSTANCE} if progress information is to
122 * be discarded.
123 *
124 * You can wait for the asynchronous download task to finish by synchronizing on the returned
125 * {@link Future}, but make sure not to freeze up JOSM. Example:
126 * <pre>
127 * Future&lt;?&gt; future = task.download(...);
128 * // DON'T run this on the Swing EDT or JOSM will freeze
129 * future.get(); // waits for the dowload task to complete
130 * </pre>
131 *
132 * The following example uses a pattern which is better suited if a task is launched from
133 * the Swing EDT:
134 * <pre>
135 * final Future&lt;?&gt; future = task.download(...);
136 * Runnable runAfterTask = new Runnable() {
137 * public void run() {
138 * // this is not strictly necessary because of the type of executor service
139 * // Main.worker is initialized with, but it doesn't harm either
140 * //
141 * future.get(); // wait for the download task to complete
142 * doSomethingAfterTheTaskCompleted();
143 * }
144 * }
145 * MainApplication.worker.submit(runAfterTask);
146 * </pre>
147 * @param reader the reader used to parse OSM data (see {@link OsmServerReader#parseOsm})
148 * @param settings download settings
149 * @param downloadArea the area to download
150 * @param progressMonitor the progressMonitor
151 * @return the future representing the asynchronous task
152 * @since 13927
153 */
154 public Future<?> download(OsmServerReader reader, DownloadParams settings, Bounds downloadArea, ProgressMonitor progressMonitor) {
155 return download(new DownloadTask(settings, reader, progressMonitor, zoomAfterDownload), downloadArea);
156 }
157
158 protected Future<?> download(DownloadTask downloadTask, Bounds downloadArea) {
159 this.downloadTask = downloadTask;
160 this.currentBounds = new Bounds(downloadArea);
161 // We need submit instead of execute so we can wait for it to finish and get the error
162 // message if necessary. If no one calls getErrorMessage() it just behaves like execute.
163 return MainApplication.worker.submit(downloadTask);
164 }
165
166 /**
167 * This allows subclasses to perform operations on the URL before {@link #loadUrl} is performed.
168 * @param url the original URL
169 * @return the modified URL
170 */
171 protected String modifyUrlBeforeLoad(String url) {
172 return url;
173 }
174
175 /**
176 * Loads a given URL from the OSM Server
177 * @param settings download settings
178 * @param url The URL as String
179 */
180 @Override
181 public Future<?> loadUrl(DownloadParams settings, String url, ProgressMonitor progressMonitor) {
182 String newUrl = modifyUrlBeforeLoad(url);
183 downloadTask = new DownloadTask(settings,
184 new OsmServerLocationReader(newUrl),
185 progressMonitor);
186 currentBounds = null;
187 // Extract .osm filename from URL to set the new layer name
188 extractOsmFilename(settings, "https?://.*/(.*\\.osm)", newUrl);
189 return MainApplication.worker.submit(downloadTask);
190 }
191
192 protected final void extractOsmFilename(DownloadParams settings, String pattern, String url) {
193 newLayerName = settings.getLayerName();
194 if (newLayerName == null || newLayerName.isEmpty()) {
195 Matcher matcher = Pattern.compile(pattern).matcher(url);
196 newLayerName = matcher.matches() ? matcher.group(1) : null;
197 }
198 }
199
200 @Override
201 public void cancel() {
202 if (downloadTask != null) {
203 downloadTask.cancel();
204 }
205 }
206
207 @Override
208 public boolean isSafeForRemotecontrolRequests() {
209 return true;
210 }
211
212 @Override
213 public ProjectionBounds getDownloadProjectionBounds() {
214 return downloadTask != null ? downloadTask.computeBbox(currentBounds) : null;
215 }
216
217 /**
218 * Superclass of internal download task.
219 * @since 7636
220 */
221 public abstract static class AbstractInternalTask extends PleaseWaitRunnable {
222
223 protected final DownloadParams settings;
224 protected final boolean zoomAfterDownload;
225 protected DataSet dataSet;
226
227 /**
228 * Constructs a new {@code AbstractInternalTask}.
229 * @param settings download settings
230 * @param title message for the user
231 * @param ignoreException If true, exception will be propagated to calling code. If false then
232 * exception will be thrown directly in EDT. When this runnable is executed using executor framework
233 * then use false unless you read result of task (because exception will get lost if you don't)
234 * @param zoomAfterDownload If true, the map view will zoom to download area after download
235 */
236 public AbstractInternalTask(DownloadParams settings, String title, boolean ignoreException, boolean zoomAfterDownload) {
237 super(title, ignoreException);
238 this.settings = Objects.requireNonNull(settings);
239 this.zoomAfterDownload = zoomAfterDownload;
240 }
241
242 /**
243 * Constructs a new {@code AbstractInternalTask}.
244 * @param settings download settings
245 * @param title message for the user
246 * @param progressMonitor progress monitor
247 * @param ignoreException If true, exception will be propagated to calling code. If false then
248 * exception will be thrown directly in EDT. When this runnable is executed using executor framework
249 * then use false unless you read result of task (because exception will get lost if you don't)
250 * @param zoomAfterDownload If true, the map view will zoom to download area after download
251 */
252 public AbstractInternalTask(DownloadParams settings, String title, ProgressMonitor progressMonitor, boolean ignoreException,
253 boolean zoomAfterDownload) {
254 super(title, progressMonitor, ignoreException);
255 this.settings = Objects.requireNonNull(settings);
256 this.zoomAfterDownload = zoomAfterDownload;
257 }
258
259 protected OsmDataLayer getEditLayer() {
260 return MainApplication.getLayerManager().getEditLayer();
261 }
262
263 private static Stream<OsmDataLayer> getModifiableDataLayers() {
264 return MainApplication.getLayerManager().getLayersOfType(OsmDataLayer.class)
265 .stream().filter(OsmDataLayer::isDownloadable);
266 }
267
268 /**
269 * Returns the number of modifiable data layers
270 * @return number of modifiable data layers
271 * @since 13434
272 */
273 protected long getNumModifiableDataLayers() {
274 return getModifiableDataLayers().count();
275 }
276
277 /**
278 * Returns the first modifiable data layer
279 * @return the first modifiable data layer
280 * @since 13434
281 */
282 protected OsmDataLayer getFirstModifiableDataLayer() {
283 return getModifiableDataLayers().findFirst().orElse(null);
284 }
285
286 protected OsmDataLayer createNewLayer(String layerName) {
287 if (layerName == null || layerName.isEmpty()) {
288 layerName = settings.getLayerName();
289 }
290 if (layerName == null || layerName.isEmpty()) {
291 layerName = OsmDataLayer.createNewName();
292 }
293 if (settings.getDownloadPolicy() != null) {
294 dataSet.setDownloadPolicy(settings.getDownloadPolicy());
295 }
296 if (settings.getUploadPolicy() != null) {
297 dataSet.setUploadPolicy(settings.getUploadPolicy());
298 }
299 if (dataSet.isLocked() && !settings.isLocked()) {
300 dataSet.unlock();
301 } else if (!dataSet.isLocked() && settings.isLocked()) {
302 dataSet.lock();
303 }
304 return new OsmDataLayer(dataSet, layerName, null);
305 }
306
307 protected OsmDataLayer createNewLayer() {
308 return createNewLayer(null);
309 }
310
311 protected ProjectionBounds computeBbox(Bounds bounds) {
312 BoundingXYVisitor v = new BoundingXYVisitor();
313 if (bounds != null) {
314 v.visit(bounds);
315 } else {
316 v.computeBoundingBox(dataSet.getNodes());
317 }
318 return v.getBounds();
319 }
320
321 protected OsmDataLayer addNewLayerIfRequired(String newLayerName) {
322 long numDataLayers = getNumModifiableDataLayers();
323 if (settings.isNewLayer() || numDataLayers == 0 || (numDataLayers > 1 && getEditLayer() == null)) {
324 // the user explicitly wants a new layer, we don't have any layer at all
325 // or it is not clear which layer to merge to
326 final OsmDataLayer layer = createNewLayer(newLayerName);
327 MainApplication.getLayerManager().addLayer(layer, zoomAfterDownload);
328 return layer;
329 }
330 return null;
331 }
332
333 protected void loadData(String newLayerName, Bounds bounds) {
334 OsmDataLayer layer = addNewLayerIfRequired(newLayerName);
335 if (layer == null) {
336 layer = getEditLayer();
337 if (layer == null || !layer.isDownloadable()) {
338 layer = getFirstModifiableDataLayer();
339 }
340 Collection<OsmPrimitive> primitivesToUpdate = searchPrimitivesToUpdate(bounds, layer.getDataSet());
341 layer.mergeFrom(dataSet);
342 MapFrame map = MainApplication.getMap();
343 if (map != null && zoomAfterDownload && bounds != null) {
344 map.mapView.zoomTo(new ViewportData(computeBbox(bounds)));
345 }
346 if (!primitivesToUpdate.isEmpty()) {
347 MainApplication.worker.submit(new UpdatePrimitivesTask(layer, primitivesToUpdate));
348 }
349 layer.onPostDownloadFromServer();
350 }
351 }
352
353 /**
354 * Look for primitives deleted on server (thus absent from downloaded data)
355 * but still present in existing data layer
356 * @param bounds download bounds
357 * @param ds existing data set
358 * @return the primitives to update
359 */
360 private Collection<OsmPrimitive> searchPrimitivesToUpdate(Bounds bounds, DataSet ds) {
361 if (bounds == null)
362 return Collections.emptySet();
363 Collection<OsmPrimitive> col = new ArrayList<>();
364 ds.searchNodes(bounds.toBBox()).stream().filter(n -> !n.isNew() && !dataSet.containsNode(n)).forEachOrdered(col::add);
365 if (!col.isEmpty()) {
366 Set<Way> ways = new HashSet<>();
367 Set<Relation> rels = new HashSet<>();
368 for (OsmPrimitive n : col) {
369 for (OsmPrimitive ref : n.getReferrers()) {
370 if (ref.isNew()) {
371 continue;
372 } else if (ref instanceof Way) {
373 ways.add((Way) ref);
374 } else if (ref instanceof Relation) {
375 rels.add((Relation) ref);
376 }
377 }
378 }
379 ways.stream().filter(w -> !dataSet.containsWay(w)).forEachOrdered(col::add);
380 rels.stream().filter(r -> !dataSet.containsRelation(r)).forEachOrdered(col::add);
381 }
382 return col;
383 }
384 }
385
386 protected class DownloadTask extends AbstractInternalTask {
387 protected final OsmServerReader reader;
388
389 /**
390 * Constructs a new {@code DownloadTask}.
391 * @param newLayer if {@code true}, force download to a new layer
392 * @param reader OSM data reader
393 * @param progressMonitor progress monitor
394 * @deprecated Use {@code DownloadTask(DownloadParams, OsmServerReader, ProgressMonitor)}
395 */
396 @Deprecated
397 public DownloadTask(boolean newLayer, OsmServerReader reader, ProgressMonitor progressMonitor) {
398 this(new DownloadParams().withNewLayer(newLayer), reader, progressMonitor);
399 }
400
401 /**
402 * Constructs a new {@code DownloadTask}.
403 * @param newLayer if {@code true}, force download to a new layer
404 * @param reader OSM data reader
405 * @param progressMonitor progress monitor
406 * @param zoomAfterDownload If true, the map view will zoom to download area after download
407 * @deprecated Use {@code DownloadTask(DownloadParams, OsmServerReader, ProgressMonitor, boolean)}
408 */
409 @Deprecated
410 public DownloadTask(boolean newLayer, OsmServerReader reader, ProgressMonitor progressMonitor, boolean zoomAfterDownload) {
411 this(new DownloadParams().withNewLayer(newLayer), reader, progressMonitor, zoomAfterDownload);
412 }
413
414 /**
415 * Constructs a new {@code DownloadTask}.
416 * @param settings download settings
417 * @param reader OSM data reader
418 * @param progressMonitor progress monitor
419 * @since 13927
420 */
421 public DownloadTask(DownloadParams settings, OsmServerReader reader, ProgressMonitor progressMonitor) {
422 this(settings, reader, progressMonitor, true);
423 }
424
425 /**
426 * Constructs a new {@code DownloadTask}.
427 * @param settings download settings
428 * @param reader OSM data reader
429 * @param progressMonitor progress monitor
430 * @param zoomAfterDownload If true, the map view will zoom to download area after download
431 * @since 13927
432 */
433 public DownloadTask(DownloadParams settings, OsmServerReader reader, ProgressMonitor progressMonitor, boolean zoomAfterDownload) {
434 super(settings, tr("Downloading data"), progressMonitor, false, zoomAfterDownload);
435 this.reader = reader;
436 }
437
438 protected DataSet parseDataSet() throws OsmTransferException {
439 return reader.parseOsm(progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
440 }
441
442 @Override
443 public void realRun() throws IOException, SAXException, OsmTransferException {
444 try {
445 if (isCanceled())
446 return;
447 dataSet = parseDataSet();
448 } catch (OsmTransferException e) {
449 if (isCanceled()) {
450 Logging.info(tr("Ignoring exception because download has been canceled. Exception was: {0}", e.toString()));
451 return;
452 }
453 if (e instanceof OsmTransferCanceledException) {
454 setCanceled(true);
455 return;
456 } else {
457 rememberException(e);
458 }
459 DownloadOsmTask.this.setFailed(true);
460 }
461 }
462
463 @Override
464 protected void finish() {
465 if (isFailed() || isCanceled())
466 return;
467 if (dataSet == null)
468 return; // user canceled download or error occurred
469 if (dataSet.allPrimitives().isEmpty()) {
470 if (warnAboutEmptyArea) {
471 rememberErrorMessage(tr("No data found in this area."));
472 }
473 String remark = dataSet.getRemark();
474 if (remark != null && !remark.isEmpty()) {
475 rememberErrorMessage(remark);
476 }
477 // need to synthesize a download bounds lest the visual indication of downloaded area doesn't work
478 dataSet.addDataSource(new DataSource(currentBounds != null ? currentBounds :
479 new Bounds(LatLon.ZERO), "OpenStreetMap server"));
480 }
481
482 rememberDownloadedData(dataSet);
483 loadData(newLayerName, currentBounds);
484 }
485
486 @Override
487 protected void cancel() {
488 setCanceled(true);
489 if (reader != null) {
490 reader.cancel();
491 }
492 }
493 }
494
495 @Override
496 public String getConfirmationMessage(URL url) {
497 if (url != null) {
498 String urlString = url.toExternalForm();
499 if (urlString.matches(OsmUrlPattern.OSM_API_URL.pattern())) {
500 // TODO: proper i18n after stabilization
501 Collection<String> items = new ArrayList<>();
502 items.add(tr("OSM Server URL:") + ' ' + url.getHost());
503 items.add(tr("Command")+": "+url.getPath());
504 if (url.getQuery() != null) {
505 items.add(tr("Request details: {0}", url.getQuery().replaceAll(",\\s*", ", ")));
506 }
507 return Utils.joinAsHtmlUnorderedList(items);
508 }
509 // TODO: other APIs
510 }
511 return null;
512 }
513}
Note: See TracBrowser for help on using the repository browser.