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

Last change on this file since 17379 was 17333, checked in by Don-vip, 3 years ago

see #20129 - Fix typos and misspellings in the code (patch by gaben)

  • Property svn:eol-style set to native
File size: 30.0 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.Collections;
13import java.util.HashSet;
14import java.util.Iterator;
15import java.util.LinkedHashMap;
16import java.util.LinkedHashSet;
17import java.util.List;
18import java.util.Map;
19import java.util.Map.Entry;
20import java.util.Set;
21import java.util.concurrent.Callable;
22import java.util.concurrent.CompletionService;
23import java.util.concurrent.ExecutionException;
24import java.util.concurrent.ExecutorCompletionService;
25import java.util.concurrent.ExecutorService;
26import java.util.concurrent.Executors;
27import java.util.concurrent.Future;
28import java.util.stream.Collectors;
29
30import org.openstreetmap.josm.data.Bounds;
31import org.openstreetmap.josm.data.osm.DataSet;
32import org.openstreetmap.josm.data.osm.DataSetMerger;
33import org.openstreetmap.josm.data.osm.Node;
34import org.openstreetmap.josm.data.osm.OsmPrimitive;
35import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
36import org.openstreetmap.josm.data.osm.PrimitiveId;
37import org.openstreetmap.josm.data.osm.Relation;
38import org.openstreetmap.josm.data.osm.RelationMember;
39import org.openstreetmap.josm.data.osm.SimplePrimitiveId;
40import org.openstreetmap.josm.data.osm.Way;
41import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
42import org.openstreetmap.josm.gui.progress.ProgressMonitor;
43import org.openstreetmap.josm.spi.preferences.Config;
44import org.openstreetmap.josm.tools.Logging;
45import org.openstreetmap.josm.tools.Utils;
46
47/**
48 * Retrieves a set of {@link OsmPrimitive}s from an OSM server using the so called
49 * Multi Fetch API.
50 *
51 * Usage:
52 * <pre>
53 * MultiFetchServerObjectReader reader = MultiFetchServerObjectReader()
54 * .append(new Node(72343));
55 * reader.parseOsm();
56 * if (!reader.getMissingPrimitives().isEmpty()) {
57 * Logging.info("There are missing primitives: " + reader.getMissingPrimitives());
58 * }
59 * if (!reader.getSkippedWays().isEmpty()) {
60 * Logging.info("There are skipped ways: " + reader.getMissingPrimitives());
61 * }
62 * </pre>
63 */
64public class MultiFetchServerObjectReader extends OsmServerReader {
65 /**
66 * the max. number of primitives retrieved in one step. Assuming IDs with 10 digits,
67 * this leads to a max. request URL of ~ 1900 Bytes ((10 digits + 1 Separator) * 170),
68 * which should be safe according to the
69 * <a href="https://web.archive.org/web/20190902193246/https://boutell.com/newfaq/misc/urllength.html">WWW FAQ</a>.
70 */
71 private static final int MAX_IDS_PER_REQUEST = 170;
72
73 private final Set<Long> nodes;
74 private final Set<Long> ways;
75 private final Set<Long> relations;
76 private final Set<PrimitiveId> missingPrimitives;
77 private final DataSet outputDataSet;
78 protected final Map<OsmPrimitiveType, Set<Long>> primitivesMap;
79
80 protected boolean recurseDownRelations;
81 private boolean recurseDownAppended = true;
82
83 /**
84 * Constructs a {@code MultiFetchServerObjectReader}.
85 */
86 protected MultiFetchServerObjectReader() {
87 nodes = new LinkedHashSet<>();
88 ways = new LinkedHashSet<>();
89 relations = new LinkedHashSet<>();
90 this.outputDataSet = new DataSet();
91 this.missingPrimitives = new LinkedHashSet<>();
92 primitivesMap = new LinkedHashMap<>();
93 primitivesMap.put(OsmPrimitiveType.RELATION, relations);
94 primitivesMap.put(OsmPrimitiveType.WAY, ways);
95 primitivesMap.put(OsmPrimitiveType.NODE, nodes);
96 }
97
98 /**
99 * Creates a new instance of {@link MultiFetchServerObjectReader} or {@link MultiFetchOverpassObjectReader}
100 * depending on the {@link OverpassDownloadReader#FOR_MULTI_FETCH preference}.
101 *
102 * @return a new instance
103 * @since 9241
104 */
105 public static MultiFetchServerObjectReader create() {
106 return create(OverpassDownloadReader.FOR_MULTI_FETCH.get());
107 }
108
109 /**
110 * Creates a new instance of {@link MultiFetchServerObjectReader} or {@link MultiFetchOverpassObjectReader}
111 * depending on the {@code fromMirror} parameter.
112 *
113 * @param fromMirror {@code false} for {@link MultiFetchServerObjectReader}, {@code true} for {@link MultiFetchOverpassObjectReader}
114 * @return a new instance
115 * @since 15520 (changed visibility)
116 */
117 public static MultiFetchServerObjectReader create(final boolean fromMirror) {
118 if (fromMirror) {
119 return new MultiFetchOverpassObjectReader();
120 } else {
121 return new MultiFetchServerObjectReader();
122 }
123 }
124
125 /**
126 * Remembers an {@link OsmPrimitive}'s id. The id will
127 * later be fetched as part of a Multi Get request.
128 *
129 * Ignore the id if it represents a new primitives.
130 *
131 * @param id the id
132 */
133 public void append(PrimitiveId id) {
134 if (id.isNew()) return;
135 switch(id.getType()) {
136 case NODE: nodes.add(id.getUniqueId()); break;
137 case WAY: ways.add(id.getUniqueId()); break;
138 case RELATION: relations.add(id.getUniqueId()); break;
139 default: throw new AssertionError();
140 }
141 }
142
143 /**
144 * appends a {@link OsmPrimitive} id to the list of ids which will be fetched from the server.
145 *
146 * @param ds the {@link DataSet} to which the primitive belongs
147 * @param id the primitive id
148 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
149 * {@link OsmPrimitiveType#RELATION RELATION}
150 * @return this
151 */
152 public MultiFetchServerObjectReader append(DataSet ds, long id, OsmPrimitiveType type) {
153 OsmPrimitive p = ds.getPrimitiveById(id, type);
154 return append(p);
155 }
156
157 /**
158 * appends a {@link Node} id to the list of ids which will be fetched from the server.
159 *
160 * @param node the node (ignored, if null)
161 * @return this
162 */
163 public MultiFetchServerObjectReader appendNode(Node node) {
164 if (node == null || node.isNew()) return this;
165 append(node.getPrimitiveId());
166 return this;
167 }
168
169 /**
170 * 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.
171 *
172 * @param way the way (ignored, if null)
173 * @return this
174 */
175 public MultiFetchServerObjectReader appendWay(Way way) {
176 if (way == null || way.isNew()) return this;
177 if (recurseDownAppended) {
178 append(way.getNodes());
179 }
180 append(way.getPrimitiveId());
181 return this;
182 }
183
184 /**
185 * appends a {@link Relation} id to the list of ids which will be fetched from the server.
186 *
187 * @param relation the relation (ignored, if null)
188 * @return this
189 */
190 protected MultiFetchServerObjectReader appendRelation(Relation relation) {
191 if (relation == null || relation.isNew()) return this;
192 append(relation.getPrimitiveId());
193 if (recurseDownAppended) {
194 for (RelationMember member : relation.getMembers()) {
195 // avoid infinite recursion in case of cyclic dependencies in relations
196 if (OsmPrimitiveType.from(member.getMember()) == OsmPrimitiveType.RELATION
197 && relations.contains(member.getMember().getId())) {
198 continue;
199 }
200 if (!member.getMember().isIncomplete()) {
201 append(member.getMember());
202 }
203 }
204 }
205 return this;
206 }
207
208 /**
209 * appends an {@link OsmPrimitive} to the list of ids which will be fetched from the server.
210 * @param primitive the primitive
211 * @return this
212 */
213 public MultiFetchServerObjectReader append(OsmPrimitive primitive) {
214 if (primitive instanceof Node) {
215 return appendNode((Node) primitive);
216 } else if (primitive instanceof Way) {
217 return appendWay((Way) primitive);
218 } else if (primitive instanceof Relation) {
219 return appendRelation((Relation) primitive);
220 }
221 return this;
222 }
223
224 /**
225 * appends a list of {@link OsmPrimitive} to the list of ids which will be fetched from the server.
226 *
227 * @param primitives the list of primitives (ignored, if null)
228 * @return this
229 *
230 * @see #append(OsmPrimitive)
231 */
232 public MultiFetchServerObjectReader append(Collection<? extends OsmPrimitive> primitives) {
233 if (primitives == null) return this;
234 primitives.forEach(this::append);
235 return this;
236 }
237
238 /**
239 * extracts a subset of max {@link #MAX_IDS_PER_REQUEST} ids from <code>ids</code> and
240 * replies the subset. The extracted subset is removed from <code>ids</code>.
241 *
242 * @param ids a set of ids
243 * @return the subset of ids
244 */
245 protected Set<Long> extractIdPackage(Set<Long> ids) {
246 Set<Long> pkg = new HashSet<>();
247 if (ids.isEmpty())
248 return pkg;
249 if (ids.size() > MAX_IDS_PER_REQUEST) {
250 Iterator<Long> it = ids.iterator();
251 for (int i = 0; i < MAX_IDS_PER_REQUEST; i++) {
252 pkg.add(it.next());
253 }
254 ids.removeAll(pkg);
255 } else {
256 pkg.addAll(ids);
257 ids.clear();
258 }
259 return pkg;
260 }
261
262 /**
263 * builds the Multi Get request string for a set of ids and a given {@link OsmPrimitiveType}.
264 *
265 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
266 * {@link OsmPrimitiveType#RELATION RELATION}
267 * @param idPackage the package of ids
268 * @return the request string
269 */
270 protected String buildRequestString(final OsmPrimitiveType type, Set<Long> idPackage) {
271 return type.getAPIName() + "s?" + type.getAPIName() + "s=" + idPackage.stream().map(String::valueOf).collect(Collectors.joining(","));
272 }
273
274 protected void rememberNodesOfIncompleteWaysToLoad(DataSet from) {
275 for (Way w: from.getWays()) {
276 for (Node n: w.getNodes()) {
277 if (n.isIncomplete()) {
278 nodes.add(n.getId());
279 }
280 }
281 }
282 }
283
284 /**
285 * merges the dataset <code>from</code> to {@link #outputDataSet}.
286 *
287 * @param from the other dataset
288 */
289 protected void merge(DataSet from) {
290 final DataSetMerger visitor = new DataSetMerger(outputDataSet, from);
291 visitor.merge();
292 }
293
294 /**
295 * fetches a set of ids of a given {@link OsmPrimitiveType} from the server
296 *
297 * @param ids the set of ids
298 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
299 * {@link OsmPrimitiveType#RELATION RELATION}
300 * @param progressMonitor progress monitor
301 * @throws OsmTransferException if an error occurs while communicating with the API server
302 */
303 protected void fetchPrimitives(Set<Long> ids, OsmPrimitiveType type, ProgressMonitor progressMonitor) throws OsmTransferException {
304 String msg;
305 final String baseUrl = getBaseUrl();
306 switch (type) {
307 // CHECKSTYLE.OFF: SingleSpaceSeparator
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 // CHECKSTYLE.ON: SingleSpaceSeparator
312 default: throw new AssertionError();
313 }
314 progressMonitor.setTicksCount(ids.size());
315 progressMonitor.setTicks(0);
316 // The complete set containing all primitives to fetch
317 Set<Long> toFetch = new HashSet<>(ids);
318 // Build a list of fetchers that will download smaller sets containing only MAX_IDS_PER_REQUEST (200) primitives each.
319 // we will run up to MAX_DOWNLOAD_THREADS concurrent fetchers.
320 int threadsNumber = Config.getPref().getInt("osm.download.threads", OsmApi.MAX_DOWNLOAD_THREADS);
321 threadsNumber = Utils.clamp(threadsNumber, 1, OsmApi.MAX_DOWNLOAD_THREADS);
322 final ExecutorService exec = Executors.newFixedThreadPool(
323 threadsNumber, Utils.newThreadFactory(getClass() + "-%d", Thread.NORM_PRIORITY));
324 CompletionService<FetchResult> ecs = new ExecutorCompletionService<>(exec);
325 List<Future<FetchResult>> jobs = new ArrayList<>();
326 while (!toFetch.isEmpty()) {
327 jobs.add(ecs.submit(new Fetcher(type, extractIdPackage(toFetch), progressMonitor)));
328 }
329 // Run the fetchers
330 for (int i = 0; i < jobs.size() && !isCanceled(); i++) {
331 progressMonitor.subTask(msg + "... " + progressMonitor.getTicks() + '/' + progressMonitor.getTicksCount());
332 try {
333 FetchResult result = ecs.take().get();
334 if (result.rc404 != null) {
335 List<Long> toSplit = new ArrayList<>(result.rc404);
336 int n = toSplit.size() / 2;
337 jobs.add(ecs.submit(new Fetcher(type, new HashSet<>(toSplit.subList(0, n)), progressMonitor)));
338 jobs.add(ecs.submit(new Fetcher(type, new HashSet<>(toSplit.subList(n, toSplit.size())), progressMonitor)));
339 }
340 if (result.missingPrimitives != null) {
341 missingPrimitives.addAll(result.missingPrimitives);
342 }
343 if (result.dataSet != null && !isCanceled()) {
344 rememberNodesOfIncompleteWaysToLoad(result.dataSet);
345 merge(result.dataSet);
346 }
347 } catch (InterruptedException | ExecutionException e) {
348 Logging.error(e);
349 if (e.getCause() instanceof OsmTransferException)
350 throw (OsmTransferException) e.getCause();
351 }
352 }
353 exec.shutdown();
354 // Cancel requests if the user chose to
355 if (isCanceled()) {
356 for (Future<FetchResult> job : jobs) {
357 job.cancel(true);
358 }
359 }
360 }
361
362 /**
363 * invokes one or more Multi Gets to fetch the {@link OsmPrimitive}s and replies
364 * the dataset of retrieved primitives. Note that the dataset includes non visible primitives too!
365 * In contrast to a simple Get for a node, a way, or a relation, a Multi Get always replies
366 * the latest version of the primitive (if any), even if the primitive is not visible (i.e. if
367 * visible==false).
368 *
369 * Invoke {@link #getMissingPrimitives()} to get a list of primitives which have not been
370 * found on the server (the server response code was 404)
371 *
372 * @return the parsed data
373 * @param progressMonitor progress monitor
374 * @throws OsmTransferException if an error occurs while communicating with the API server
375 * @see #getMissingPrimitives()
376 *
377 */
378 @Override
379 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
380 missingPrimitives.clear();
381 int n = nodes.size() + ways.size() + relations.size();
382 progressMonitor.beginTask(trn("Downloading {0} object from ''{1}''",
383 "Downloading {0} objects from ''{1}''", n, n, getBaseUrl()));
384 try {
385 if (this instanceof MultiFetchOverpassObjectReader) {
386 // calculate a single request for all the objects
387 String request = MultiFetchOverpassObjectReader.genOverpassQuery(primitivesMap, true, false, recurseDownRelations);
388 if (isCanceled())
389 return null;
390 OverpassDownloadReader reader = new OverpassDownloadReader(new Bounds(0, 0, 0, 0), getBaseUrl(), request);
391 DataSet ds = reader.parseOsm(progressMonitor.createSubTaskMonitor(1, false));
392 new DataSetMerger(outputDataSet, ds).merge();
393 checkMissing(outputDataSet, progressMonitor);
394 } else {
395 downloadRelations(progressMonitor);
396 if (isCanceled())
397 return null;
398 fetchPrimitives(ways, OsmPrimitiveType.WAY, progressMonitor);
399 if (isCanceled())
400 return null;
401 fetchPrimitives(nodes, OsmPrimitiveType.NODE, progressMonitor);
402 }
403 outputDataSet.deleteInvisible();
404 return outputDataSet;
405 } finally {
406 progressMonitor.finishTask();
407 }
408 }
409
410 /**
411 * Workaround for difference in Overpass API.
412 * As of now (version 7.55) Overpass api doesn't return invisible objects.
413 * Check if we have objects which do not appear in the dataset and fetch them from OSM instead.
414 * @param ds the dataset
415 * @param progressMonitor progress monitor
416 * @throws OsmTransferException if an error occurs while communicating with the API server
417 */
418 private void checkMissing(DataSet ds, ProgressMonitor progressMonitor) throws OsmTransferException {
419 Set<OsmPrimitive> missing = new LinkedHashSet<>();
420 for (Entry<OsmPrimitiveType, Set<Long>> e : primitivesMap.entrySet()) {
421 for (long id : e.getValue()) {
422 if (ds.getPrimitiveById(id, e.getKey()) == null)
423 missing.add(e.getKey().newInstance(id, true));
424 }
425 }
426 if (isCanceled() || missing.isEmpty())
427 return;
428
429 MultiFetchServerObjectReader missingReader = MultiFetchServerObjectReader.create(false);
430 missingReader.setRecurseDownAppended(false);
431 missingReader.setRecurseDownRelations(false);
432 missingReader.append(missing);
433 DataSet mds = missingReader.parseOsm(progressMonitor.createSubTaskMonitor(missing.size(), false));
434 new DataSetMerger(ds, mds).merge();
435 missingPrimitives.addAll(missingReader.getMissingPrimitives());
436 }
437
438 /**
439 * Finds best way to download a set of relations.
440 * @param progressMonitor progress monitor
441 * @throws OsmTransferException if an error occurs while communicating with the API server
442 * @see #getMissingPrimitives()
443 */
444 private void downloadRelations(ProgressMonitor progressMonitor) throws OsmTransferException {
445 Set<Long> toDownload = new LinkedHashSet<>(relations);
446 fetchPrimitives(toDownload, OsmPrimitiveType.RELATION, progressMonitor);
447 if (!recurseDownRelations) {
448 return;
449 }
450 // OSM multi-fetch api may return invisible objects, we don't try to get details for them
451 for (Relation r : outputDataSet.getRelations()) {
452 if (!r.isVisible())
453 toDownload.remove(r.getUniqueId());
454 }
455 // fetch full info for all visible relations
456 for (long id : toDownload) {
457 if (isCanceled())
458 return;
459 OsmServerObjectReader reader = new OsmServerObjectReader(id, OsmPrimitiveType.RELATION, true/* full*/);
460 DataSet ds = reader.parseOsm(progressMonitor.createSubTaskMonitor(1, false));
461 merge(ds);
462 }
463 }
464
465 /**
466 * replies the set of ids of all primitives for which a fetch request to the
467 * server was submitted but which are not available from the server (the server
468 * replied a return code of 404)
469 *
470 * @return the set of ids of missing primitives
471 */
472 public Set<PrimitiveId> getMissingPrimitives() {
473 return missingPrimitives;
474 }
475
476 /**
477 * Should downloaded relations be complete?
478 * @param recurseDownRelations true: yes, recurse down to retrieve the members of the relation
479 * This will download sub relations, complete way members and nodes. Members of sub relations are not
480 * retrieved unless they are also members of the relations. See #18835.
481 * @return this
482 * @since 15811
483 */
484 public MultiFetchServerObjectReader setRecurseDownRelations(boolean recurseDownRelations) {
485 this.recurseDownRelations = recurseDownRelations;
486 return this;
487 }
488
489 /**
490 * Determine how appended objects are treated. By default, all children of an appended object are also appended.
491 * @param recurseAppended false: do not append known children of appended objects, i.e. all nodes of way and all members of a relation
492 * @return this
493 * @since 15811
494 */
495 public MultiFetchServerObjectReader setRecurseDownAppended(boolean recurseAppended) {
496 this.recurseDownAppended = recurseAppended;
497 return this;
498 }
499
500 /**
501 * The class holding the results given by {@link Fetcher}.
502 * It is only a wrapper of the resulting {@link DataSet} and the collection of {@link PrimitiveId} that could not have been loaded.
503 */
504 protected static class FetchResult {
505
506 /**
507 * The resulting data set
508 */
509 public final DataSet dataSet;
510
511 /**
512 * The collection of primitive ids that could not have been loaded
513 */
514 public final Set<PrimitiveId> missingPrimitives;
515
516 private Set<Long> rc404;
517
518 /**
519 * Constructs a {@code FetchResult}
520 * @param dataSet The resulting data set
521 * @param missingPrimitives The collection of primitive ids that could not have been loaded
522 */
523 public FetchResult(DataSet dataSet, Set<PrimitiveId> missingPrimitives) {
524 this.dataSet = dataSet;
525 this.missingPrimitives = missingPrimitives;
526 }
527 }
528
529 /**
530 * The class that actually download data from OSM API.
531 * Several instances of this class are used by {@link MultiFetchServerObjectReader} (one per set of primitives to fetch).
532 * The inheritance of {@link OsmServerReader} is only explained by the need to have a distinct OSM connection by {@code Fetcher} instance.
533 * @see FetchResult
534 */
535 protected class Fetcher extends OsmServerReader implements Callable<FetchResult> {
536
537 private final Set<Long> pkg;
538 private final OsmPrimitiveType type;
539 private final ProgressMonitor progressMonitor;
540
541 /**
542 * Constructs a {@code Fetcher}
543 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
544 * {@link OsmPrimitiveType#RELATION RELATION}
545 * @param idsPackage The set of primitives ids to fetch
546 * @param progressMonitor The progress monitor
547 */
548 public Fetcher(OsmPrimitiveType type, Set<Long> idsPackage, ProgressMonitor progressMonitor) {
549 this.pkg = idsPackage;
550 this.type = type;
551 this.progressMonitor = progressMonitor;
552 }
553
554 @Override
555 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
556 // This method is implemented because of the OsmServerReader inheritance, but not used,
557 // as the main target of this class is the call() method.
558 return fetch(progressMonitor).dataSet;
559 }
560
561 @Override
562 public FetchResult call() throws Exception {
563 return fetch(progressMonitor);
564 }
565
566 /**
567 * fetches the requested primitives and updates the specified progress monitor.
568 * @param progressMonitor the progress monitor
569 * @return the {@link FetchResult} of this operation
570 * @throws OsmTransferException if an error occurs while communicating with the API server
571 */
572 protected FetchResult fetch(ProgressMonitor progressMonitor) throws OsmTransferException {
573 try {
574 return multiGetIdPackage(type, pkg, progressMonitor);
575 } catch (OsmApiException e) {
576 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
577 if (pkg.size() > 4) {
578 FetchResult res = new FetchResult(null, null);
579 res.rc404 = pkg;
580 return res;
581 }
582 if (pkg.size() == 1) {
583 FetchResult res = new FetchResult(new DataSet(), new HashSet<PrimitiveId>());
584 res.missingPrimitives.add(new SimplePrimitiveId(pkg.iterator().next(), type));
585 return res;
586 } else {
587 Logging.info(tr("Server replied with response code 404, retrying with an individual request for each object."));
588 return singleGetIdPackage(type, pkg, progressMonitor);
589 }
590 } else {
591 throw e;
592 }
593 }
594 }
595
596 @Override
597 protected String getBaseUrl() {
598 return MultiFetchServerObjectReader.this.getBaseUrl();
599 }
600
601 /**
602 * invokes a Multi Get for a set of ids and a given {@link OsmPrimitiveType}.
603 * The retrieved primitives are merged to {@link #outputDataSet}.
604 *
605 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
606 * {@link OsmPrimitiveType#RELATION RELATION}
607 * @param pkg the package of ids
608 * @param progressMonitor progress monitor
609 * @return the {@link FetchResult} of this operation
610 * @throws OsmTransferException if an error occurs while communicating with the API server
611 */
612 protected FetchResult multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor)
613 throws OsmTransferException {
614 String request = buildRequestString(type, pkg);
615 FetchResult result = null;
616 try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
617 if (in == null) return null;
618 progressMonitor.subTask(tr("Downloading OSM data..."));
619 try {
620 result = new FetchResult(OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(pkg.size(), false)), null);
621 } catch (IllegalDataException e) {
622 throw new OsmTransferException(e);
623 }
624 } catch (IOException ex) {
625 Logging.warn(ex);
626 throw new OsmTransferException(ex);
627 }
628 return result;
629 }
630
631 /**
632 * invokes a Multi Get for a single id and a given {@link OsmPrimitiveType}.
633 * The retrieved primitive is merged to {@link #outputDataSet}.
634 *
635 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
636 * {@link OsmPrimitiveType#RELATION RELATION}
637 * @param id the id
638 * @param progressMonitor progress monitor
639 * @return the {@link DataSet} resulting of this operation
640 * @throws OsmTransferException if an error occurs while communicating with the API server
641 */
642 protected DataSet singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException {
643 String request = buildRequestString(type, Collections.singleton(id));
644 DataSet result = null;
645 try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
646 if (in == null) return null;
647 progressMonitor.subTask(tr("Downloading OSM data..."));
648 try {
649 result = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
650 } catch (IllegalDataException e) {
651 throw new OsmTransferException(e);
652 }
653 } catch (IOException ex) {
654 Logging.warn(ex);
655 }
656 return result;
657 }
658
659 /**
660 * invokes a sequence of Multi Gets for individual ids in a set of ids and a given {@link OsmPrimitiveType}.
661 * The retrieved primitives are merged to {@link #outputDataSet}.
662 *
663 * This method is used if one of the ids in pkg doesn't exist (the server replies with return code 404).
664 * If the set is fetched with this method it is possible to find out which of the ids doesn't exist.
665 * Unfortunately, the server does not provide an error header or an error body for a 404 reply.
666 *
667 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY},
668 * {@link OsmPrimitiveType#RELATION RELATION}
669 * @param pkg the set of ids
670 * @param progressMonitor progress monitor
671 * @return the {@link FetchResult} of this operation
672 * @throws OsmTransferException if an error occurs while communicating with the API server
673 */
674 protected FetchResult singleGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor)
675 throws OsmTransferException {
676 FetchResult result = new FetchResult(new DataSet(), new HashSet<PrimitiveId>());
677 String baseUrl = OsmApi.getOsmApi().getBaseUrl();
678 for (long id : pkg) {
679 try {
680 String msg;
681 switch (type) {
682 // CHECKSTYLE.OFF: SingleSpaceSeparator
683 case NODE: msg = tr("Fetching node with id {0} from ''{1}''", id, baseUrl); break;
684 case WAY: msg = tr("Fetching way with id {0} from ''{1}''", id, baseUrl); break;
685 case RELATION: msg = tr("Fetching relation with id {0} from ''{1}''", id, baseUrl); break;
686 // CHECKSTYLE.ON: SingleSpaceSeparator
687 default: throw new AssertionError();
688 }
689 progressMonitor.setCustomText(msg);
690 result.dataSet.mergeFrom(singleGetId(type, id, progressMonitor));
691 } catch (OsmApiException e) {
692 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
693 Logging.info(tr("Server replied with response code 404 for id {0}. Skipping.", Long.toString(id)));
694 result.missingPrimitives.add(new SimplePrimitiveId(id, type));
695 } else {
696 throw e;
697 }
698 }
699 }
700 return result;
701 }
702 }
703}
Note: See TracBrowser for help on using the repository browser.