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

Last change on this file since 2025 was 2025, checked in by Gubaer, 15 years ago

new: improved dialog for uploading/saving modified layers on exit
new: improved dialog for uploading/saving modified layers if layers are deleted
new: new progress monitor which can delegate rendering to any Swing component
more setters/getters for properties in OSM data classes (fields are @deprecated); started to update references in the code base

File size: 18.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;
5
6import java.io.InputStream;
7import java.net.HttpURLConnection;
8import java.util.Collection;
9import java.util.HashSet;
10import java.util.Iterator;
11import java.util.NoSuchElementException;
12import java.util.Set;
13import java.util.logging.Logger;
14
15import org.openstreetmap.josm.data.osm.DataSet;
16import org.openstreetmap.josm.data.osm.Node;
17import org.openstreetmap.josm.data.osm.OsmPrimitive;
18import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
19import org.openstreetmap.josm.data.osm.Relation;
20import org.openstreetmap.josm.data.osm.RelationMember;
21import org.openstreetmap.josm.data.osm.Way;
22import org.openstreetmap.josm.data.osm.visitor.MergeVisitor;
23import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
24import org.openstreetmap.josm.gui.progress.ProgressMonitor;
25
26/**
27 * Retrieves a set of {@see OsmPrimitive}s from an OSM server using the so called
28 * Multi Fetch API.
29 *
30 * Usage:
31 * <pre>
32 * MultiFetchServerObjectReader reader = MultiFetchServerObjectReader()
33 * .append(2345,2334,4444)
34 * .append(new Node(72343));
35 * reader.parseOsm();
36 * if (!reader.getMissingPrimitives().isEmpty()) {
37 * System.out.println("There are missing primitives: " + reader.getMissingPrimitives());
38 * }
39 * if (!reader.getSkippedWays().isEmpty()) {
40 * System.out.println("There are skipped ways: " + reader.getMissingPrimitives());
41 * }
42 * </pre>
43 *
44 *
45 */
46public class MultiFetchServerObjectReader extends OsmServerReader{
47
48 static private Logger logger = Logger.getLogger(MultiFetchServerObjectReader.class.getName());
49 /**
50 * the max. number of primitives retrieved in one step. Assuming IDs with 7 digits,
51 * this leads to a max. request URL of ~ 1600 Bytes ((7 digits + 1 Seperator) * 200),
52 * which should be safe according to the
53 * <a href="http://www.boutell.com/newfaq/misc/urllength.html">WWW FAQ</a>.
54 *
55 */
56 static private int MAX_IDS_PER_REQUEST = 200;
57
58
59 private HashSet<Long> nodes;
60 private HashSet<Long> ways;
61 private HashSet<Long> relations;
62 private HashSet<Long> missingPrimitives;
63 private DataSet outputDataSet;
64
65 private boolean cancelled = false;
66
67 /**
68 * constructor
69 *
70 */
71 public MultiFetchServerObjectReader() {
72 nodes = new HashSet<Long>();
73 ways = new HashSet<Long>();
74 relations = new HashSet<Long>();
75 this.outputDataSet = new DataSet();
76 this.missingPrimitives = new HashSet<Long>();
77 }
78
79 /**
80 * remembers an {@see OsmPrimitive}'s id and its type. The id will
81 * later be fetched as part of a Multi Get request.
82 *
83 * Ignore the id if it id <= 0.
84 *
85 * @param id the id
86 * @param type the type
87 */
88 protected void remember(long id, OsmPrimitiveType type) {
89 if (id <= 0) return;
90 if (type.equals(OsmPrimitiveType.NODE)) {
91 nodes.add(id);
92 } else if (type.equals(OsmPrimitiveType.WAY)) {
93 ways.add(id);
94 } if (type.equals(OsmPrimitiveType.RELATION)) {
95 relations.add(id);
96 }
97 }
98
99 /**
100 * remembers an {@see OsmPrimitive}'s id. <code>ds</code> must include
101 * an {@see OsmPrimitive} with id=<code>id</code>. The id will
102 * later we fetched as part of a Multi Get request.
103 *
104 * Ignore the id if it id <= 0.
105 *
106 * @param ds the dataset (must not be null)
107 * @param id the id
108 * @exception IllegalArgumentException thrown, if ds is null
109 * @exception NoSuchElementException thrown, if ds doesn't include an {@see OsmPrimitive} with
110 * id=<code>id</code>
111 */
112 protected void remember(DataSet ds, long id) throws IllegalArgumentException, NoSuchElementException{
113 if (ds == null)
114 throw new IllegalArgumentException(tr("parameter ''{0}'' must not be null", "ds"));
115 if (id <= 0) return;
116 OsmPrimitive primitive = ds.getPrimitiveById(id);
117 if (primitive == null)
118 throw new NoSuchElementException(tr("no primitive with id {0} in local dataset. Can't infer primitive type", id));
119 remember(id, OsmPrimitiveType.from(primitive));
120 return;
121 }
122
123 /**
124 * appends a list of ids to the list of ids which will be fetched from the server. ds must
125 * include an {@see OsmPrimitive} for each id in ids.
126 *
127 * id is ignored if id <= 0.
128 *
129 * @param ds the dataset
130 * @param ids the list of ids
131 * @return this
132 *
133 */
134 public MultiFetchServerObjectReader append(DataSet ds, long ... ids) {
135 if (ids == null) return this;
136 for (int i=0; i < ids.length; i++) {
137 remember(ds, ids[i]);
138 }
139 return this;
140 }
141
142 /**
143 * appends a collection of ids to the list of ids which will be fetched from the server. ds must
144 * include an {@see OsmPrimitive} for each id in ids.
145 *
146 * id is ignored if id <= 0.
147 *
148 * @param ds the dataset
149 * @param ids the collection of ids
150 * @return this
151 *
152 */
153 public MultiFetchServerObjectReader append(DataSet ds, Collection<Long> ids) {
154 if (ids == null) return null;
155 for (long id: ids) {
156 append(ds,id);
157 }
158 return this;
159 }
160
161 /**
162 * appends a {@see Node}s id to the list of ids which will be fetched from the server.
163 *
164 * @param node the node (ignored, if null)
165 * @return this
166 *
167 */
168 public MultiFetchServerObjectReader append(Node node) {
169 if (node == null) return this;
170 if (node.getId() == 0) return this;
171 remember(node.getId(), OsmPrimitiveType.NODE);
172 return this;
173 }
174
175 /**
176 * appends a {@see Way}s id and the list of ids of nodes the way refers to to the list of ids which will be fetched from the server.
177 *
178 * @param way the way (ignored, if null)
179 * @return this
180 *
181 */
182 public MultiFetchServerObjectReader append(Way way) {
183 if (way == null) return this;
184 if (way.getId() == 0) return this;
185 for (Node node: way.getNodes()) {
186 if (node.getId() > 0) {
187 remember(node.getId(), OsmPrimitiveType.NODE);
188 }
189 }
190 remember(way.getId(), OsmPrimitiveType.WAY);
191 return this;
192 }
193
194 /**
195 * appends a {@see Relation}s id to the list of ids which will be fetched from the server.
196 *
197 * @param relation the relation (ignored, if null)
198 * @return this
199 *
200 */
201 public MultiFetchServerObjectReader append(Relation relation) {
202 if (relation == null) return this;
203 if (relation.getId() == 0) return this;
204 remember(relation.getId(), OsmPrimitiveType.RELATION);
205 for (RelationMember member : relation.getMembers()) {
206 if (OsmPrimitiveType.from(member.member).equals(OsmPrimitiveType.RELATION)) {
207 // avoid infinite recursion in case of cyclic dependencies in relations
208 //
209 if (relations.contains(member.member.getId())) {
210 continue;
211 }
212 }
213 appendGeneric(member.getMember());
214 }
215 return this;
216 }
217
218 protected MultiFetchServerObjectReader appendGeneric(OsmPrimitive primitive) {
219 if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.NODE))
220 return append((Node)primitive);
221 else if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.WAY))
222 return append((Way)primitive);
223 else if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.RELATION))
224 return append((Relation)primitive);
225
226 return this;
227 }
228
229 /**
230 * appends a list of {@see OsmPrimitive} to the list of ids which will be fetched from the server.
231 *
232 * @param primitives the list of primitives (ignored, if null)
233 * @return this
234 *
235 * @see #append(Node)
236 * @see #append(Way)
237 * @see #append(Relation)
238 *
239 */
240 public MultiFetchServerObjectReader append(Collection<? extends OsmPrimitive> primitives) {
241 if (primitives == null) return this;
242 for (OsmPrimitive primitive : primitives) {
243 appendGeneric(primitive);
244 }
245 return this;
246 }
247
248 /**
249 * extracts a subset of max {@see #MAX_IDS_PER_REQUEST} ids from <code>ids</code> and
250 * replies the subset. The extracted subset is removed from <code>ids</code>.
251 *
252 * @param ids a set of ids
253 * @return the subset of ids
254 */
255 protected Set<Long> extractIdPackage(Set<Long> ids) {
256 HashSet<Long> pkg = new HashSet<Long>();
257 if (ids.isEmpty())
258 return pkg;
259 if (ids.size() > MAX_IDS_PER_REQUEST) {
260 Iterator<Long> it = ids.iterator();
261 for (int i =0;i<MAX_IDS_PER_REQUEST;i++) {
262 pkg.add(it.next());
263 }
264 ids.removeAll(pkg);
265 } else {
266 pkg.addAll(ids);
267 ids.clear();
268 }
269 return pkg;
270 }
271
272
273 /**
274 * builds the Multi Get request string for a set of ids and a given
275 * {@see OsmPrimitiveType}.
276 *
277 * @param type the type
278 * @param idPackage the package of ids
279 * @return the request string
280 */
281 protected String buildRequestString(OsmPrimitiveType type, Set<Long> idPackage) {
282 StringBuilder sb = new StringBuilder();
283 sb.append(type.getAPIName()).append("s?")
284 .append(type.getAPIName()).append("s=");
285
286 Iterator<Long> it = idPackage.iterator();
287 for (int i=0; i< idPackage.size();i++) {
288 sb.append(it.next());
289 if (i < idPackage.size()-1) {
290 sb.append(",");
291 }
292 }
293 return sb.toString();
294 }
295
296 /**
297 * builds the Multi Get request string for a single id and a given
298 * {@see OsmPrimitiveType}.
299 *
300 * @param type the type
301 * @param id the id
302 * @return the request string
303 */
304 protected String buildRequestString(OsmPrimitiveType type, long id) {
305 StringBuilder sb = new StringBuilder();
306 sb.append(type.getAPIName()).append("s?")
307 .append(type.getAPIName()).append("s=")
308 .append(id);
309 return sb.toString();
310 }
311
312 /**
313 * invokes a Multi Get for a set of ids and a given {@see OsmPrimitiveType}.
314 * The retrieved primitives are merged to {@see #outputDataSet}.
315 *
316 * @param type the type
317 * @param pkg the package of ids
318 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
319 *
320 */
321 protected void multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException {
322 String request = buildRequestString(type, pkg);
323 final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
324 if (in == null) return;
325 progressMonitor.subTask(tr("Downloading OSM data..."));
326 try {
327 final OsmReader osm = OsmReader.parseDataSetOsm(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
328 merge(osm.getDs());
329 } catch(Exception e) {
330 throw new OsmTransferException(e);
331 }
332 }
333
334 /**
335 * invokes a Multi Get for a single id and a given {@see OsmPrimitiveType}.
336 * The retrieved primitive is merged to {@see #outputDataSet}.
337 *
338 * @param type the type
339 * @param id the id
340 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
341 *
342 */
343 protected void singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException {
344 String request = buildRequestString(type, id);
345 final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
346 if (in == null)
347 return;
348 progressMonitor.subTask(tr("Downloading OSM data..."));
349 try {
350 final OsmReader osm = OsmReader.parseDataSetOsm(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
351 merge(osm.getDs());
352 } catch(Exception e) {
353 throw new OsmTransferException(e);
354 }
355 }
356
357 /**
358 * invokes a sequence of Multi Gets for individual ids in a set of ids and a given {@see OsmPrimitiveType}.
359 * The retrieved primitives are merged to {@see #outputDataSet}.
360 *
361 * This method is used if one of the ids in pkg doesn't exist (the server replies with return code 404).
362 * If the set is fetched with this method it is possible to find out which of the ids doesn't exist.
363 * Unfortunatelly, the server does not provide an error header or an error body for a 404 reply.
364 *
365 * @param type the type
366 * @param pkg the set of ids
367 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
368 *
369 */
370 protected void singleGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException {
371 for (long id : pkg) {
372 try {
373 String msg = "";
374 switch(type) {
375 case NODE: msg = tr("Fetching node with id {0} from ''{1}''", id, OsmApi.getOsmApi().getBaseUrl()); break;
376 case WAY: msg = tr("Fetching way with id {0} from ''{1}''", id, OsmApi.getOsmApi().getBaseUrl()); break;
377 case RELATION: msg = tr("Fetching relation with id {0} from ''{1}''", id, OsmApi.getOsmApi().getBaseUrl()); break;
378 }
379 progressMonitor.setCustomText(msg);
380 singleGetId(type, id, progressMonitor);
381 } catch(OsmApiException e) {
382 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
383 logger.warning(tr("Server replied with response code 404 for id {0}. Skipping.", Long.toString(id)));
384 missingPrimitives.add(id);
385 continue;
386 }
387 throw e;
388 }
389 }
390 }
391
392 /**
393 * merges the dataset <code>from</code> to {@see #outputDataSet}.
394 *
395 * @param from the other dataset
396 *
397 */
398 protected void merge(DataSet from) {
399 final MergeVisitor visitor = new MergeVisitor(outputDataSet,from);
400 visitor.merge();
401 }
402
403 /**
404 * fetches a set of ids of a given {@see OsmPrimitiveType} from the server
405 *
406 * @param ids the set of ids
407 * @param type the type
408 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
409 */
410 protected void fetchPrimitives(Set<Long> ids, OsmPrimitiveType type, ProgressMonitor progressMonitor) throws OsmTransferException{
411 String msg = "";
412 switch(type) {
413 case NODE: msg = tr("Fetching a package of nodes from ''{0}''", OsmApi.getOsmApi().getBaseUrl()); break;
414 case WAY: msg = tr("Fetching a package of ways from ''{0}''", OsmApi.getOsmApi().getBaseUrl()); break;
415 case RELATION: msg = tr("Fetching a package of relations from ''{0}''", OsmApi.getOsmApi().getBaseUrl()); break;
416 }
417 progressMonitor.setCustomText(msg);
418 Set<Long> toFetch = new HashSet<Long>(ids);
419 toFetch.addAll(ids);
420 while(! toFetch.isEmpty() && !isCanceled()) {
421 Set<Long> pkg = extractIdPackage(toFetch);
422 try {
423 multiGetIdPackage(type, pkg, progressMonitor);
424 } catch(OsmApiException e) {
425 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
426 logger.warning(tr("Server replied with response code 404, retrying with an individual request for each primitive"));
427 singleGetIdPackage(type, pkg, progressMonitor);
428 } else
429 throw e;
430 }
431 }
432 }
433
434 /**
435 * invokes one or more Multi Gets to fetch the {@see OsmPrimitive}s and replies
436 * the dataset of retrieved primitives. Note that the dataset includes non visible primitives too!
437 * In contrast to a simple Get for a node, a way, or a relation, a Multi Get always replies
438 * the latest version of the primitive (if any), even if the primitive is not visible (i.e. if
439 * visible==false).
440 *
441 * Invoke {@see #getMissingPrimitives()} to get a list of primitives which have not been
442 * found on the server (the server response code was 404)
443 *
444 * Invoke {@see #getSkippedWay()} to get a list of ways which this reader could not build from
445 * the fetched data because the ways refer to nodes which don't exist on the server.
446 *
447 * @return the parsed data
448 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
449 * @see #getMissingPrimitives()
450 * @see #getSkippedWays()
451 *
452
453 */
454 @Override
455 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
456 progressMonitor.beginTask("");
457 try {
458 missingPrimitives = new HashSet<Long>();
459 if (isCanceled())return null;
460 fetchPrimitives(nodes,OsmPrimitiveType.NODE, progressMonitor);
461 if (isCanceled())return null;
462 fetchPrimitives(ways,OsmPrimitiveType.WAY, progressMonitor);
463 if (isCanceled())return null;
464 fetchPrimitives(relations,OsmPrimitiveType.RELATION, progressMonitor);
465 return outputDataSet;
466 } finally {
467 progressMonitor.finishTask();
468 }
469 }
470
471 /**
472 * replies the set of ids of all primitives for which a fetch request to the
473 * server was submitted but which are not available from the server (the server
474 * replied a return code of 404)
475 *
476 * @return the set of ids of missing primitives
477 */
478 public Set<Long> getMissingPrimitives() {
479 return missingPrimitives;
480 }
481}
Note: See TracBrowser for help on using the repository browser.