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

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

see #8039, see #10456 - support read-only data layers

  • Property svn:eol-style set to native
File size: 17.9 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.Optional;
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 @Override
80 public Future<?> download(boolean newLayer, Bounds downloadArea, ProgressMonitor progressMonitor) {
81 return download(new BoundingBoxDownloader(downloadArea), newLayer, downloadArea, progressMonitor);
82 }
83
84 /**
85 * Asynchronously launches the download task for a given bounding box.
86 *
87 * Set <code>progressMonitor</code> to null, if the task should create, open, and close a progress monitor.
88 * Set progressMonitor to {@link NullProgressMonitor#INSTANCE} if progress information is to
89 * be discarded.
90 *
91 * You can wait for the asynchronous download task to finish by synchronizing on the returned
92 * {@link Future}, but make sure not to freeze up JOSM. Example:
93 * <pre>
94 * Future&lt;?&gt; future = task.download(...);
95 * // DON'T run this on the Swing EDT or JOSM will freeze
96 * future.get(); // waits for the dowload task to complete
97 * </pre>
98 *
99 * The following example uses a pattern which is better suited if a task is launched from
100 * the Swing EDT:
101 * <pre>
102 * final Future&lt;?&gt; future = task.download(...);
103 * Runnable runAfterTask = new Runnable() {
104 * public void run() {
105 * // this is not strictly necessary because of the type of executor service
106 * // Main.worker is initialized with, but it doesn't harm either
107 * //
108 * future.get(); // wait for the download task to complete
109 * doSomethingAfterTheTaskCompleted();
110 * }
111 * }
112 * MainApplication.worker.submit(runAfterTask);
113 * </pre>
114 * @param reader the reader used to parse OSM data (see {@link OsmServerReader#parseOsm})
115 * @param newLayer true, if the data is to be downloaded into a new layer. If false, the task
116 * selects one of the existing layers as download layer, preferably the active layer.
117 * @param downloadArea the area to download
118 * @param progressMonitor the progressMonitor
119 * @return the future representing the asynchronous task
120 */
121 public Future<?> download(OsmServerReader reader, boolean newLayer, Bounds downloadArea, ProgressMonitor progressMonitor) {
122 return download(new DownloadTask(newLayer, reader, progressMonitor, zoomAfterDownload), downloadArea);
123 }
124
125 protected Future<?> download(DownloadTask downloadTask, Bounds downloadArea) {
126 this.downloadTask = downloadTask;
127 this.currentBounds = new Bounds(downloadArea);
128 // We need submit instead of execute so we can wait for it to finish and get the error
129 // message if necessary. If no one calls getErrorMessage() it just behaves like execute.
130 return MainApplication.worker.submit(downloadTask);
131 }
132
133 /**
134 * This allows subclasses to perform operations on the URL before {@link #loadUrl} is performed.
135 * @param url the original URL
136 * @return the modified URL
137 */
138 protected String modifyUrlBeforeLoad(String url) {
139 return url;
140 }
141
142 /**
143 * Loads a given URL from the OSM Server
144 * @param newLayer True if the data should be saved to a new layer
145 * @param url The URL as String
146 */
147 @Override
148 public Future<?> loadUrl(boolean newLayer, String url, ProgressMonitor progressMonitor) {
149 String newUrl = modifyUrlBeforeLoad(url);
150 downloadTask = new DownloadTask(newLayer,
151 new OsmServerLocationReader(newUrl),
152 progressMonitor);
153 currentBounds = null;
154 // Extract .osm filename from URL to set the new layer name
155 extractOsmFilename("https?://.*/(.*\\.osm)", newUrl);
156 return MainApplication.worker.submit(downloadTask);
157 }
158
159 protected final void extractOsmFilename(String pattern, String url) {
160 Matcher matcher = Pattern.compile(pattern).matcher(url);
161 newLayerName = matcher.matches() ? matcher.group(1) : null;
162 }
163
164 @Override
165 public void cancel() {
166 if (downloadTask != null) {
167 downloadTask.cancel();
168 }
169 }
170
171 @Override
172 public boolean isSafeForRemotecontrolRequests() {
173 return true;
174 }
175
176 @Override
177 public ProjectionBounds getDownloadProjectionBounds() {
178 return downloadTask != null ? downloadTask.computeBbox(currentBounds) : null;
179 }
180
181 /**
182 * Superclass of internal download task.
183 * @since 7636
184 */
185 public abstract static class AbstractInternalTask extends PleaseWaitRunnable {
186
187 protected final boolean newLayer;
188 protected final boolean zoomAfterDownload;
189 protected DataSet dataSet;
190
191 /**
192 * Constructs a new {@code AbstractInternalTask}.
193 *
194 * @param newLayer if {@code true}, force download to a new layer
195 * @param title message for the user
196 * @param ignoreException If true, exception will be propagated to calling code. If false then
197 * exception will be thrown directly in EDT. When this runnable is executed using executor framework
198 * then use false unless you read result of task (because exception will get lost if you don't)
199 * @param zoomAfterDownload If true, the map view will zoom to download area after download
200 */
201 public AbstractInternalTask(boolean newLayer, String title, boolean ignoreException, boolean zoomAfterDownload) {
202 super(title, ignoreException);
203 this.newLayer = newLayer;
204 this.zoomAfterDownload = zoomAfterDownload;
205 }
206
207 /**
208 * Constructs a new {@code AbstractInternalTask}.
209 *
210 * @param newLayer if {@code true}, force download to a new layer
211 * @param title message for the user
212 * @param progressMonitor progress monitor
213 * @param ignoreException If true, exception will be propagated to calling code. If false then
214 * exception will be thrown directly in EDT. When this runnable is executed using executor framework
215 * then use false unless you read result of task (because exception will get lost if you don't)
216 * @param zoomAfterDownload If true, the map view will zoom to download area after download
217 */
218 public AbstractInternalTask(boolean newLayer, String title, ProgressMonitor progressMonitor, boolean ignoreException,
219 boolean zoomAfterDownload) {
220 super(title, progressMonitor, ignoreException);
221 this.newLayer = newLayer;
222 this.zoomAfterDownload = zoomAfterDownload;
223 }
224
225 protected OsmDataLayer getEditLayer() {
226 if (!MainApplication.isDisplayingMapView()) return null;
227 return MainApplication.getLayerManager().getEditLayer();
228 }
229
230 /**
231 * Returns the number of modifiable data layers
232 * @return number of modifiable data layers
233 * @deprecated Use {@link #getNumModifiableDataLayers}
234 */
235 @Deprecated
236 protected int getNumDataLayers() {
237 return (int) getNumModifiableDataLayers();
238 }
239
240 private static Stream<OsmDataLayer> getModifiableDataLayers() {
241 return MainApplication.getLayerManager().getLayersOfType(OsmDataLayer.class)
242 .stream().filter(l -> !l.isReadOnly());
243 }
244
245 /**
246 * Returns the number of modifiable data layers
247 * @return number of modifiable data layers
248 * @since 13434
249 */
250 protected long getNumModifiableDataLayers() {
251 return getModifiableDataLayers().count();
252 }
253
254 /**
255 * Returns the first modifiable data layer
256 * @return the first modifiable data layer
257 * @since 13434
258 */
259 protected OsmDataLayer getFirstModifiableDataLayer() {
260 return getModifiableDataLayers().findFirst().orElse(null);
261 }
262
263 protected OsmDataLayer createNewLayer(String layerName) {
264 if (layerName == null || layerName.isEmpty()) {
265 layerName = OsmDataLayer.createNewName();
266 }
267 return new OsmDataLayer(dataSet, layerName, null);
268 }
269
270 protected OsmDataLayer createNewLayer() {
271 return createNewLayer(null);
272 }
273
274 protected ProjectionBounds computeBbox(Bounds bounds) {
275 BoundingXYVisitor v = new BoundingXYVisitor();
276 if (bounds != null) {
277 v.visit(bounds);
278 } else {
279 v.computeBoundingBox(dataSet.getNodes());
280 }
281 return v.getBounds();
282 }
283
284 protected OsmDataLayer addNewLayerIfRequired(String newLayerName) {
285 long numDataLayers = getNumModifiableDataLayers();
286 if (newLayer || numDataLayers == 0 || (numDataLayers > 1 && getEditLayer() == null)) {
287 // the user explicitly wants a new layer, we don't have any layer at all
288 // or it is not clear which layer to merge to
289 //
290 final OsmDataLayer layer = createNewLayer(newLayerName);
291 MainApplication.getLayerManager().addLayer(layer, zoomAfterDownload);
292 return layer;
293 }
294 return null;
295 }
296
297 protected void loadData(String newLayerName, Bounds bounds) {
298 OsmDataLayer layer = addNewLayerIfRequired(newLayerName);
299 if (layer == null) {
300 layer = Optional.ofNullable(getEditLayer()).orElseGet(this::getFirstModifiableDataLayer);
301 Collection<OsmPrimitive> primitivesToUpdate = searchPrimitivesToUpdate(bounds, layer.data);
302 layer.mergeFrom(dataSet);
303 MapFrame map = MainApplication.getMap();
304 if (map != null && zoomAfterDownload && bounds != null) {
305 map.mapView.zoomTo(new ViewportData(computeBbox(bounds)));
306 }
307 if (!primitivesToUpdate.isEmpty()) {
308 MainApplication.worker.submit(new UpdatePrimitivesTask(layer, primitivesToUpdate));
309 }
310 layer.onPostDownloadFromServer();
311 }
312 }
313
314 /**
315 * Look for primitives deleted on server (thus absent from downloaded data)
316 * but still present in existing data layer
317 * @param bounds download bounds
318 * @param ds existing data set
319 * @return the primitives to update
320 */
321 private Collection<OsmPrimitive> searchPrimitivesToUpdate(Bounds bounds, DataSet ds) {
322 if (bounds == null)
323 return Collections.emptySet();
324 Collection<OsmPrimitive> col = new ArrayList<>();
325 ds.searchNodes(bounds.toBBox()).stream().filter(n -> !n.isNew() && !dataSet.containsNode(n)).forEachOrdered(col::add);
326 if (!col.isEmpty()) {
327 Set<Way> ways = new HashSet<>();
328 Set<Relation> rels = new HashSet<>();
329 for (OsmPrimitive n : col) {
330 for (OsmPrimitive ref : n.getReferrers()) {
331 if (ref.isNew()) {
332 continue;
333 } else if (ref instanceof Way) {
334 ways.add((Way) ref);
335 } else if (ref instanceof Relation) {
336 rels.add((Relation) ref);
337 }
338 }
339 }
340 ways.stream().filter(w -> !dataSet.containsWay(w)).forEachOrdered(col::add);
341 rels.stream().filter(r -> !dataSet.containsRelation(r)).forEachOrdered(col::add);
342 }
343 return col;
344 }
345 }
346
347 protected class DownloadTask extends AbstractInternalTask {
348 protected final OsmServerReader reader;
349
350 /**
351 * Constructs a new {@code DownloadTask}.
352 * @param newLayer if {@code true}, force download to a new layer
353 * @param reader OSM data reader
354 * @param progressMonitor progress monitor
355 */
356 public DownloadTask(boolean newLayer, OsmServerReader reader, ProgressMonitor progressMonitor) {
357 this(newLayer, reader, progressMonitor, true);
358 }
359
360 /**
361 * Constructs a new {@code DownloadTask}.
362 * @param newLayer if {@code true}, force download to a new layer
363 * @param reader OSM data reader
364 * @param progressMonitor progress monitor
365 * @param zoomAfterDownload If true, the map view will zoom to download area after download
366 * @since 8942
367 */
368 public DownloadTask(boolean newLayer, OsmServerReader reader, ProgressMonitor progressMonitor, boolean zoomAfterDownload) {
369 super(newLayer, tr("Downloading data"), progressMonitor, false, zoomAfterDownload);
370 this.reader = reader;
371 }
372
373 protected DataSet parseDataSet() throws OsmTransferException {
374 return reader.parseOsm(progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
375 }
376
377 @Override
378 public void realRun() throws IOException, SAXException, OsmTransferException {
379 try {
380 if (isCanceled())
381 return;
382 dataSet = parseDataSet();
383 } catch (OsmTransferException e) {
384 if (isCanceled()) {
385 Logging.info(tr("Ignoring exception because download has been canceled. Exception was: {0}", e.toString()));
386 return;
387 }
388 if (e instanceof OsmTransferCanceledException) {
389 setCanceled(true);
390 return;
391 } else {
392 rememberException(e);
393 }
394 DownloadOsmTask.this.setFailed(true);
395 }
396 }
397
398 @Override
399 protected void finish() {
400 if (isFailed() || isCanceled())
401 return;
402 if (dataSet == null)
403 return; // user canceled download or error occurred
404 if (dataSet.allPrimitives().isEmpty()) {
405 if (warnAboutEmptyArea) {
406 rememberErrorMessage(tr("No data found in this area."));
407 }
408 // need to synthesize a download bounds lest the visual indication of downloaded area doesn't work
409 dataSet.addDataSource(new DataSource(currentBounds != null ? currentBounds :
410 new Bounds(LatLon.ZERO), "OpenStreetMap server"));
411 }
412
413 rememberDownloadedData(dataSet);
414 loadData(newLayerName, currentBounds);
415 }
416
417 @Override
418 protected void cancel() {
419 setCanceled(true);
420 if (reader != null) {
421 reader.cancel();
422 }
423 }
424 }
425
426 @Override
427 public String getConfirmationMessage(URL url) {
428 if (url != null) {
429 String urlString = url.toExternalForm();
430 if (urlString.matches(OsmUrlPattern.OSM_API_URL.pattern())) {
431 // TODO: proper i18n after stabilization
432 Collection<String> items = new ArrayList<>();
433 items.add(tr("OSM Server URL:") + ' ' + url.getHost());
434 items.add(tr("Command")+": "+url.getPath());
435 if (url.getQuery() != null) {
436 items.add(tr("Request details: {0}", url.getQuery().replaceAll(",\\s*", ", ")));
437 }
438 return Utils.joinAsHtmlUnorderedList(items);
439 }
440 // TODO: other APIs
441 }
442 return null;
443 }
444}
Note: See TracBrowser for help on using the repository browser.