source: josm/trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java@ 9231

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

javadoc update

  • Property svn:eol-style set to native
File size: 23.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.io.IOException;
8import java.io.InputStream;
9import java.net.HttpURLConnection;
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.HashSet;
13import java.util.Iterator;
14import java.util.LinkedHashSet;
15import java.util.List;
16import java.util.Set;
17import java.util.concurrent.Callable;
18import java.util.concurrent.CompletionService;
19import java.util.concurrent.ExecutionException;
20import java.util.concurrent.Executor;
21import java.util.concurrent.ExecutorCompletionService;
22import java.util.concurrent.Executors;
23import java.util.concurrent.Future;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.data.osm.DataSet;
27import org.openstreetmap.josm.data.osm.DataSetMerger;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
31import org.openstreetmap.josm.data.osm.PrimitiveId;
32import org.openstreetmap.josm.data.osm.Relation;
33import org.openstreetmap.josm.data.osm.RelationMember;
34import org.openstreetmap.josm.data.osm.SimplePrimitiveId;
35import org.openstreetmap.josm.data.osm.Way;
36import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
37import org.openstreetmap.josm.gui.progress.ProgressMonitor;
38import org.openstreetmap.josm.tools.Utils;
39
40/**
41 * Retrieves a set of {@link OsmPrimitive}s from an OSM server using the so called
42 * Multi Fetch API.
43 *
44 * Usage:
45 * <pre>
46 * MultiFetchServerObjectReader reader = MultiFetchServerObjectReader()
47 * .append(2345,2334,4444)
48 * .append(new Node(72343));
49 * reader.parseOsm();
50 * if (!reader.getMissingPrimitives().isEmpty()) {
51 * Main.info("There are missing primitives: " + reader.getMissingPrimitives());
52 * }
53 * if (!reader.getSkippedWays().isEmpty()) {
54 * Main.info("There are skipped ways: " + reader.getMissingPrimitives());
55 * }
56 * </pre>
57 */
58public class MultiFetchServerObjectReader extends OsmServerReader {
59 /**
60 * the max. number of primitives retrieved in one step. Assuming IDs with 7 digits,
61 * this leads to a max. request URL of ~ 1600 Bytes ((7 digits + 1 Separator) * 200),
62 * which should be safe according to the
63 * <a href="http://www.boutell.com/newfaq/misc/urllength.html">WWW FAQ</a>.
64 */
65 private static final int MAX_IDS_PER_REQUEST = 200;
66
67 private final Set<Long> nodes;
68 private final Set<Long> ways;
69 private final Set<Long> relations;
70 private Set<PrimitiveId> missingPrimitives;
71 private final DataSet outputDataSet;
72
73 /**
74 * Constructs a {@code MultiFetchServerObjectReader}.
75 */
76 public MultiFetchServerObjectReader() {
77 nodes = new LinkedHashSet<>();
78 ways = new LinkedHashSet<>();
79 relations = new LinkedHashSet<>();
80 this.outputDataSet = new DataSet();
81 this.missingPrimitives = new LinkedHashSet<>();
82 }
83
84 /**
85 * Remembers an {@link OsmPrimitive}'s id. The id will
86 * later be fetched as part of a Multi Get request.
87 *
88 * Ignore the id if it represents a new primitives.
89 *
90 * @param id the id
91 */
92 protected void remember(PrimitiveId id) {
93 if (id.isNew()) return;
94 switch(id.getType()) {
95 case NODE: nodes.add(id.getUniqueId()); break;
96 case WAY: ways.add(id.getUniqueId()); break;
97 case RELATION: relations.add(id.getUniqueId()); break;
98 }
99 }
100
101 /**
102 * appends a {@link OsmPrimitive} id to the list of ids which will be fetched from the server.
103 *
104 * @param ds the {@link DataSet} to which the primitive belongs
105 * @param id the primitive id
106 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
107 * {@link OsmPrimitiveType#RELATION RELATION}
108 * @return this
109 */
110 public MultiFetchServerObjectReader append(DataSet ds, long id, OsmPrimitiveType type) {
111 OsmPrimitive p = ds.getPrimitiveById(id, type);
112 switch(type) {
113 case NODE:
114 return appendNode((Node) p);
115 case WAY:
116 return appendWay((Way) p);
117 case RELATION:
118 return appendRelation((Relation) p);
119 }
120 return this;
121 }
122
123 /**
124 * appends a {@link Node} id to the list of ids which will be fetched from the server.
125 *
126 * @param node the node (ignored, if null)
127 * @return this
128 */
129 public MultiFetchServerObjectReader appendNode(Node node) {
130 if (node == null) return this;
131 remember(node.getPrimitiveId());
132 return this;
133 }
134
135 /**
136 * appends a {@link Way} id and the list of ids of nodes the way refers to the list of ids which will be fetched from the server.
137 *
138 * @param way the way (ignored, if null)
139 * @return this
140 */
141 public MultiFetchServerObjectReader appendWay(Way way) {
142 if (way == null) return this;
143 if (way.isNew()) return this;
144 for (Node node: way.getNodes()) {
145 if (!node.isNew()) {
146 remember(node.getPrimitiveId());
147 }
148 }
149 remember(way.getPrimitiveId());
150 return this;
151 }
152
153 /**
154 * appends a {@link Relation} id to the list of ids which will be fetched from the server.
155 *
156 * @param relation the relation (ignored, if null)
157 * @return this
158 */
159 protected MultiFetchServerObjectReader appendRelation(Relation relation) {
160 if (relation == null) return this;
161 if (relation.isNew()) return this;
162 remember(relation.getPrimitiveId());
163 for (RelationMember member : relation.getMembers()) {
164 if (OsmPrimitiveType.from(member.getMember()).equals(OsmPrimitiveType.RELATION)) {
165 // avoid infinite recursion in case of cyclic dependencies in relations
166 //
167 if (relations.contains(member.getMember().getId())) {
168 continue;
169 }
170 }
171 if (!member.getMember().isIncomplete()) {
172 append(member.getMember());
173 }
174 }
175 return this;
176 }
177
178 /**
179 * appends an {@link OsmPrimitive} to the list of ids which will be fetched from the server.
180 * @param primitive the primitive
181 * @return this
182 */
183 public MultiFetchServerObjectReader append(OsmPrimitive primitive) {
184 if (primitive != null) {
185 switch (OsmPrimitiveType.from(primitive)) {
186 case NODE: return appendNode((Node) primitive);
187 case WAY: return appendWay((Way) primitive);
188 case RELATION: return appendRelation((Relation) primitive);
189 }
190 }
191 return this;
192 }
193
194 /**
195 * appends a list of {@link OsmPrimitive} to the list of ids which will be fetched from the server.
196 *
197 * @param primitives the list of primitives (ignored, if null)
198 * @return this
199 *
200 * @see #append(OsmPrimitive)
201 */
202 public MultiFetchServerObjectReader append(Collection<? extends OsmPrimitive> primitives) {
203 if (primitives == null) return this;
204 for (OsmPrimitive primitive : primitives) {
205 append(primitive);
206 }
207 return this;
208 }
209
210 /**
211 * extracts a subset of max {@link #MAX_IDS_PER_REQUEST} ids from <code>ids</code> and
212 * replies the subset. The extracted subset is removed from <code>ids</code>.
213 *
214 * @param ids a set of ids
215 * @return the subset of ids
216 */
217 protected Set<Long> extractIdPackage(Set<Long> ids) {
218 Set<Long> pkg = new HashSet<>();
219 if (ids.isEmpty())
220 return pkg;
221 if (ids.size() > MAX_IDS_PER_REQUEST) {
222 Iterator<Long> it = ids.iterator();
223 for (int i = 0; i < MAX_IDS_PER_REQUEST; i++) {
224 pkg.add(it.next());
225 }
226 ids.removeAll(pkg);
227 } else {
228 pkg.addAll(ids);
229 ids.clear();
230 }
231 return pkg;
232 }
233
234 /**
235 * builds the Multi Get request string for a set of ids and a given {@link OsmPrimitiveType}.
236 *
237 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
238 * {@link OsmPrimitiveType#RELATION RELATION}
239 * @param idPackage the package of ids
240 * @return the request string
241 */
242 protected static String buildRequestString(OsmPrimitiveType type, Set<Long> idPackage) {
243 StringBuilder sb = new StringBuilder();
244 sb.append(type.getAPIName()).append("s?")
245 .append(type.getAPIName()).append("s=");
246
247 Iterator<Long> it = idPackage.iterator();
248 for (int i = 0; i < idPackage.size(); i++) {
249 sb.append(it.next());
250 if (i < idPackage.size()-1) {
251 sb.append(',');
252 }
253 }
254 return sb.toString();
255 }
256
257 /**
258 * builds the Multi Get request string for a single id and a given {@link OsmPrimitiveType}.
259 *
260 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
261 * {@link OsmPrimitiveType#RELATION RELATION}
262 * @param id the id
263 * @return the request string
264 */
265 protected static String buildRequestString(OsmPrimitiveType type, long id) {
266 StringBuilder sb = new StringBuilder();
267 sb.append(type.getAPIName()).append("s?")
268 .append(type.getAPIName()).append("s=")
269 .append(id);
270 return sb.toString();
271 }
272
273 protected void rememberNodesOfIncompleteWaysToLoad(DataSet from) {
274 for (Way w: from.getWays()) {
275 if (w.hasIncompleteNodes()) {
276 for (Node n: w.getNodes()) {
277 if (n.isIncomplete()) {
278 nodes.add(n.getId());
279 }
280 }
281 }
282 }
283 }
284
285 /**
286 * merges the dataset <code>from</code> to {@link #outputDataSet}.
287 *
288 * @param from the other dataset
289 */
290 protected void merge(DataSet from) {
291 final DataSetMerger visitor = new DataSetMerger(outputDataSet, from);
292 visitor.merge();
293 }
294
295 /**
296 * fetches a set of ids of a given {@link OsmPrimitiveType} from the server
297 *
298 * @param ids the set of ids
299 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
300 * {@link OsmPrimitiveType#RELATION RELATION}
301 * @param progressMonitor progress monitor
302 * @throws OsmTransferException if an error occurs while communicating with the API server
303 */
304 protected void fetchPrimitives(Set<Long> ids, OsmPrimitiveType type, ProgressMonitor progressMonitor) throws OsmTransferException {
305 String msg = "";
306 String baseUrl = OsmApi.getOsmApi().getBaseUrl();
307 switch (type) {
308 case NODE: msg = tr("Fetching a package of nodes from ''{0}''", baseUrl); break;
309 case WAY: msg = tr("Fetching a package of ways from ''{0}''", baseUrl); break;
310 case RELATION: msg = tr("Fetching a package of relations from ''{0}''", baseUrl); break;
311 }
312 progressMonitor.setTicksCount(ids.size());
313 progressMonitor.setTicks(0);
314 // The complete set containing all primitives to fetch
315 Set<Long> toFetch = new HashSet<>(ids);
316 // Build a list of fetchers that will download smaller sets containing only MAX_IDS_PER_REQUEST (200) primitives each.
317 // we will run up to MAX_DOWNLOAD_THREADS concurrent fetchers.
318 int threadsNumber = Main.pref.getInteger("osm.download.threads", OsmApi.MAX_DOWNLOAD_THREADS);
319 threadsNumber = Math.min(Math.max(threadsNumber, 1), OsmApi.MAX_DOWNLOAD_THREADS);
320 Executor exec = Executors.newFixedThreadPool(threadsNumber, Utils.newThreadFactory(getClass() + "-%d", Thread.NORM_PRIORITY));
321 CompletionService<FetchResult> ecs = new ExecutorCompletionService<>(exec);
322 List<Future<FetchResult>> jobs = new ArrayList<>();
323 while (!toFetch.isEmpty()) {
324 jobs.add(ecs.submit(new Fetcher(type, extractIdPackage(toFetch), progressMonitor)));
325 }
326 // Run the fetchers
327 for (int i = 0; i < jobs.size() && !isCanceled(); i++) {
328 progressMonitor.subTask(msg + "... " + progressMonitor.getTicks() + '/' + progressMonitor.getTicksCount());
329 try {
330 FetchResult result = ecs.take().get();
331 if (result.missingPrimitives != null) {
332 missingPrimitives.addAll(result.missingPrimitives);
333 }
334 if (result.dataSet != null && !isCanceled()) {
335 rememberNodesOfIncompleteWaysToLoad(result.dataSet);
336 merge(result.dataSet);
337 }
338 } catch (InterruptedException | ExecutionException e) {
339 Main.error(e);
340 }
341 }
342 // Cancel requests if the user choosed to
343 if (isCanceled()) {
344 for (Future<FetchResult> job : jobs) {
345 job.cancel(true);
346 }
347 }
348 }
349
350 /**
351 * invokes one or more Multi Gets to fetch the {@link OsmPrimitive}s and replies
352 * the dataset of retrieved primitives. Note that the dataset includes non visible primitives too!
353 * In contrast to a simple Get for a node, a way, or a relation, a Multi Get always replies
354 * the latest version of the primitive (if any), even if the primitive is not visible (i.e. if
355 * visible==false).
356 *
357 * Invoke {@link #getMissingPrimitives()} to get a list of primitives which have not been
358 * found on the server (the server response code was 404)
359 *
360 * @return the parsed data
361 * @throws OsmTransferException if an error occurs while communicating with the API server
362 * @see #getMissingPrimitives()
363 *
364 */
365 @Override
366 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
367 int n = nodes.size() + ways.size() + relations.size();
368 progressMonitor.beginTask(trn("Downloading {0} object from ''{1}''",
369 "Downloading {0} objects from ''{1}''", n, n, OsmApi.getOsmApi().getBaseUrl()));
370 try {
371 missingPrimitives = new HashSet<>();
372 if (isCanceled()) return null;
373 fetchPrimitives(ways, OsmPrimitiveType.WAY, progressMonitor);
374 if (isCanceled()) return null;
375 fetchPrimitives(nodes, OsmPrimitiveType.NODE, progressMonitor);
376 if (isCanceled()) return null;
377 fetchPrimitives(relations, OsmPrimitiveType.RELATION, progressMonitor);
378 if (outputDataSet != null) {
379 outputDataSet.deleteInvisible();
380 }
381 return outputDataSet;
382 } finally {
383 progressMonitor.finishTask();
384 }
385 }
386
387 /**
388 * replies the set of ids of all primitives for which a fetch request to the
389 * server was submitted but which are not available from the server (the server
390 * replied a return code of 404)
391 *
392 * @return the set of ids of missing primitives
393 */
394 public Set<PrimitiveId> getMissingPrimitives() {
395 return missingPrimitives;
396 }
397
398 /**
399 * The class holding the results given by {@link Fetcher}.
400 * It is only a wrapper of the resulting {@link DataSet} and the collection of {@link PrimitiveId} that could not have been loaded.
401 */
402 protected static class FetchResult {
403
404 /**
405 * The resulting data set
406 */
407 public final DataSet dataSet;
408
409 /**
410 * The collection of primitive ids that could not have been loaded
411 */
412 public final Set<PrimitiveId> missingPrimitives;
413
414 /**
415 * Constructs a {@code FetchResult}
416 * @param dataSet The resulting data set
417 * @param missingPrimitives The collection of primitive ids that could not have been loaded
418 */
419 public FetchResult(DataSet dataSet, Set<PrimitiveId> missingPrimitives) {
420 this.dataSet = dataSet;
421 this.missingPrimitives = missingPrimitives;
422 }
423 }
424
425 /**
426 * The class that actually download data from OSM API.
427 * Several instances of this class are used by {@link MultiFetchServerObjectReader} (one per set of primitives to fetch).
428 * The inheritance of {@link OsmServerReader} is only explained by the need to have a distinct OSM connection by {@code Fetcher} instance.
429 * @see FetchResult
430 */
431 protected static class Fetcher extends OsmServerReader implements Callable<FetchResult> {
432
433 private final Set<Long> pkg;
434 private final OsmPrimitiveType type;
435 private final ProgressMonitor progressMonitor;
436
437 /**
438 * Constructs a {@code Fetcher}
439 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
440 * {@link OsmPrimitiveType#RELATION RELATION}
441 * @param idsPackage The set of primitives ids to fetch
442 * @param progressMonitor The progress monitor
443 */
444 public Fetcher(OsmPrimitiveType type, Set<Long> idsPackage, ProgressMonitor progressMonitor) {
445 this.pkg = idsPackage;
446 this.type = type;
447 this.progressMonitor = progressMonitor;
448 }
449
450 @Override
451 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
452 // This method is implemented because of the OsmServerReader inheritance, but not used,
453 // as the main target of this class is the call() method.
454 return fetch(progressMonitor).dataSet;
455 }
456
457 @Override
458 public FetchResult call() throws Exception {
459 return fetch(progressMonitor);
460 }
461
462 /**
463 * fetches the requested primitives and updates the specified progress monitor.
464 * @param progressMonitor the progress monitor
465 * @return the {@link FetchResult} of this operation
466 * @throws OsmTransferException if an error occurs while communicating with the API server
467 */
468 protected FetchResult fetch(ProgressMonitor progressMonitor) throws OsmTransferException {
469 try {
470 return multiGetIdPackage(type, pkg, progressMonitor);
471 } catch (OsmApiException e) {
472 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
473 Main.info(tr("Server replied with response code 404, retrying with an individual request for each object."));
474 return singleGetIdPackage(type, pkg, progressMonitor);
475 } else {
476 throw e;
477 }
478 }
479 }
480
481 /**
482 * invokes a Multi Get for a set of ids and a given {@link OsmPrimitiveType}.
483 * The retrieved primitives are merged to {@link #outputDataSet}.
484 *
485 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
486 * {@link OsmPrimitiveType#RELATION RELATION}
487 * @param pkg the package of ids
488 * @param progressMonitor progress monitor
489 * @return the {@link FetchResult} of this operation
490 * @throws OsmTransferException if an error occurs while communicating with the API server
491 */
492 protected FetchResult multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor)
493 throws OsmTransferException {
494 String request = buildRequestString(type, pkg);
495 FetchResult result = null;
496 try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
497 if (in == null) return null;
498 progressMonitor.subTask(tr("Downloading OSM data..."));
499 try {
500 result = new FetchResult(OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(pkg.size(), false)), null);
501 } catch (Exception e) {
502 throw new OsmTransferException(e);
503 }
504 } catch (IOException ex) {
505 Main.warn(ex);
506 }
507 return result;
508 }
509
510 /**
511 * invokes a Multi Get for a single id and a given {@link OsmPrimitiveType}.
512 * The retrieved primitive is merged to {@link #outputDataSet}.
513 *
514 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
515 * {@link OsmPrimitiveType#RELATION RELATION}
516 * @param id the id
517 * @param progressMonitor progress monitor
518 * @return the {@link DataSet} resulting of this operation
519 * @throws OsmTransferException if an error occurs while communicating with the API server
520 */
521 protected DataSet singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException {
522 String request = buildRequestString(type, id);
523 DataSet result = null;
524 try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
525 if (in == null) return null;
526 progressMonitor.subTask(tr("Downloading OSM data..."));
527 try {
528 result = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
529 } catch (Exception e) {
530 throw new OsmTransferException(e);
531 }
532 } catch (IOException ex) {
533 Main.warn(ex);
534 }
535 return result;
536 }
537
538 /**
539 * invokes a sequence of Multi Gets for individual ids in a set of ids and a given {@link OsmPrimitiveType}.
540 * The retrieved primitives are merged to {@link #outputDataSet}.
541 *
542 * This method is used if one of the ids in pkg doesn't exist (the server replies with return code 404).
543 * If the set is fetched with this method it is possible to find out which of the ids doesn't exist.
544 * Unfortunately, the server does not provide an error header or an error body for a 404 reply.
545 *
546 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
547 * {@link OsmPrimitiveType#RELATION RELATION}
548 * @param pkg the set of ids
549 * @param progressMonitor progress monitor
550 * @return the {@link FetchResult} of this operation
551 * @throws OsmTransferException if an error occurs while communicating with the API server
552 */
553 protected FetchResult singleGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor)
554 throws OsmTransferException {
555 FetchResult result = new FetchResult(new DataSet(), new HashSet<PrimitiveId>());
556 String baseUrl = OsmApi.getOsmApi().getBaseUrl();
557 for (long id : pkg) {
558 try {
559 String msg = "";
560 switch (type) {
561 case NODE: msg = tr("Fetching node with id {0} from ''{1}''", id, baseUrl); break;
562 case WAY: msg = tr("Fetching way with id {0} from ''{1}''", id, baseUrl); break;
563 case RELATION: msg = tr("Fetching relation with id {0} from ''{1}''", id, baseUrl); break;
564 }
565 progressMonitor.setCustomText(msg);
566 result.dataSet.mergeFrom(singleGetId(type, id, progressMonitor));
567 } catch (OsmApiException e) {
568 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
569 Main.info(tr("Server replied with response code 404 for id {0}. Skipping.", Long.toString(id)));
570 result.missingPrimitives.add(new SimplePrimitiveId(id, type));
571 } else {
572 throw e;
573 }
574 }
575 }
576 return result;
577 }
578 }
579}
Note: See TracBrowser for help on using the repository browser.