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

Last change on this file since 7026 was 7005, checked in by Don-vip, 10 years ago

see #8465 - use diamond operator where applicable

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