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

Last change on this file since 2474 was 2433, checked in by Gubaer, 14 years ago

Improved test cases for MergeVisitor.
Moved MergeVisitor and removed Visitor-pattern. Double-dispatching isn't necessary and only slows down the merge process.

File size: 17.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;
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.DataSetMerger;
17import org.openstreetmap.josm.data.osm.Node;
18import org.openstreetmap.josm.data.osm.OsmPrimitive;
19import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
20import org.openstreetmap.josm.data.osm.Relation;
21import org.openstreetmap.josm.data.osm.RelationMember;
22import org.openstreetmap.josm.data.osm.Way;
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, OsmPrimitiveType type) 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, type);
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 {@see Node}s 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 */
130 public MultiFetchServerObjectReader append(DataSet ds, long id, OsmPrimitiveType type) {
131 switch(type) {
132 case NODE:
133 Node n = (Node)ds.getPrimitiveById(id,type);
134 append(n);
135 break;
136 case WAY:
137 Way w= (Way)ds.getPrimitiveById(id,type);
138 append(w);
139 break;
140 case RELATION:
141 Relation r = (Relation)ds.getPrimitiveById(id,type);
142 append(r);
143 break;
144 }
145 return this;
146 }
147
148 /**
149 * appends a {@see Node}s id to the list of ids which will be fetched from the server.
150 *
151 * @param node the node (ignored, if null)
152 * @return this
153 *
154 */
155 public MultiFetchServerObjectReader append(Node node) {
156 if (node == null) return this;
157 if (node.isNew()) return this;
158 remember(node.getId(), OsmPrimitiveType.NODE);
159 return this;
160 }
161
162 /**
163 * 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.
164 *
165 * @param way the way (ignored, if null)
166 * @return this
167 *
168 */
169 public MultiFetchServerObjectReader append(Way way) {
170 if (way == null) return this;
171 if (way.isNew()) return this;
172 for (Node node: way.getNodes()) {
173 if (!node.isNew()) {
174 remember(node.getId(), OsmPrimitiveType.NODE);
175 }
176 }
177 remember(way.getId(), OsmPrimitiveType.WAY);
178 return this;
179 }
180
181 /**
182 * appends a {@see Relation}s id to the list of ids which will be fetched from the server.
183 *
184 * @param relation the relation (ignored, if null)
185 * @return this
186 *
187 */
188 public MultiFetchServerObjectReader append(Relation relation) {
189 if (relation == null) return this;
190 if (relation.isNew()) return this;
191 remember(relation.getId(), OsmPrimitiveType.RELATION);
192 for (RelationMember member : relation.getMembers()) {
193 if (OsmPrimitiveType.from(member.getMember()).equals(OsmPrimitiveType.RELATION)) {
194 // avoid infinite recursion in case of cyclic dependencies in relations
195 //
196 if (relations.contains(member.getMember().getId())) {
197 continue;
198 }
199 }
200 appendGeneric(member.getMember());
201 }
202 return this;
203 }
204
205 protected MultiFetchServerObjectReader appendGeneric(OsmPrimitive primitive) {
206 if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.NODE))
207 return append((Node)primitive);
208 else if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.WAY))
209 return append((Way)primitive);
210 else if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.RELATION))
211 return append((Relation)primitive);
212
213 return this;
214 }
215
216 /**
217 * appends a list of {@see 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(Node)
223 * @see #append(Way)
224 * @see #append(Relation)
225 *
226 */
227 public MultiFetchServerObjectReader append(Collection<? extends OsmPrimitive> primitives) {
228 if (primitives == null) return this;
229 for (OsmPrimitive primitive : primitives) {
230 appendGeneric(primitive);
231 }
232 return this;
233 }
234
235 /**
236 * extracts a subset of max {@see #MAX_IDS_PER_REQUEST} ids from <code>ids</code> and
237 * replies the subset. The extracted subset is removed from <code>ids</code>.
238 *
239 * @param ids a set of ids
240 * @return the subset of ids
241 */
242 protected Set<Long> extractIdPackage(Set<Long> ids) {
243 HashSet<Long> pkg = new HashSet<Long>();
244 if (ids.isEmpty())
245 return pkg;
246 if (ids.size() > MAX_IDS_PER_REQUEST) {
247 Iterator<Long> it = ids.iterator();
248 for (int i =0;i<MAX_IDS_PER_REQUEST;i++) {
249 pkg.add(it.next());
250 }
251 ids.removeAll(pkg);
252 } else {
253 pkg.addAll(ids);
254 ids.clear();
255 }
256 return pkg;
257 }
258
259
260 /**
261 * builds the Multi Get request string for a set of ids and a given
262 * {@see OsmPrimitiveType}.
263 *
264 * @param type the type
265 * @param idPackage the package of ids
266 * @return the request string
267 */
268 protected String buildRequestString(OsmPrimitiveType type, Set<Long> idPackage) {
269 StringBuilder sb = new StringBuilder();
270 sb.append(type.getAPIName()).append("s?")
271 .append(type.getAPIName()).append("s=");
272
273 Iterator<Long> it = idPackage.iterator();
274 for (int i=0; i< idPackage.size();i++) {
275 sb.append(it.next());
276 if (i < idPackage.size()-1) {
277 sb.append(",");
278 }
279 }
280 return sb.toString();
281 }
282
283 /**
284 * builds the Multi Get request string for a single id and a given
285 * {@see OsmPrimitiveType}.
286 *
287 * @param type the type
288 * @param id the id
289 * @return the request string
290 */
291 protected String buildRequestString(OsmPrimitiveType type, long id) {
292 StringBuilder sb = new StringBuilder();
293 sb.append(type.getAPIName()).append("s?")
294 .append(type.getAPIName()).append("s=")
295 .append(id);
296 return sb.toString();
297 }
298
299 /**
300 * invokes a Multi Get for a set of ids and a given {@see OsmPrimitiveType}.
301 * The retrieved primitives are merged to {@see #outputDataSet}.
302 *
303 * @param type the type
304 * @param pkg the package of ids
305 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
306 *
307 */
308 protected void multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException {
309 String request = buildRequestString(type, pkg);
310 final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
311 if (in == null) return;
312 progressMonitor.subTask(tr("Downloading OSM data..."));
313 try {
314
315 merge(
316 OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false))
317 );
318 } catch(Exception e) {
319 throw new OsmTransferException(e);
320 }
321 }
322
323 /**
324 * invokes a Multi Get for a single id and a given {@see OsmPrimitiveType}.
325 * The retrieved primitive is merged to {@see #outputDataSet}.
326 *
327 * @param type the type
328 * @param id the id
329 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
330 *
331 */
332 protected void singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException {
333 String request = buildRequestString(type, id);
334 final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
335 if (in == null)
336 return;
337 progressMonitor.subTask(tr("Downloading OSM data..."));
338 try {
339 merge(
340 OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false))
341 );
342 } catch(Exception e) {
343 throw new OsmTransferException(e);
344 }
345 }
346
347 /**
348 * invokes a sequence of Multi Gets for individual ids in a set of ids and a given {@see OsmPrimitiveType}.
349 * The retrieved primitives are merged to {@see #outputDataSet}.
350 *
351 * This method is used if one of the ids in pkg doesn't exist (the server replies with return code 404).
352 * If the set is fetched with this method it is possible to find out which of the ids doesn't exist.
353 * Unfortunatelly, the server does not provide an error header or an error body for a 404 reply.
354 *
355 * @param type the type
356 * @param pkg the set of ids
357 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
358 *
359 */
360 protected void singleGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException {
361 for (long id : pkg) {
362 try {
363 String msg = "";
364 switch(type) {
365 case NODE: msg = tr("Fetching node with id {0} from ''{1}''", id, OsmApi.getOsmApi().getBaseUrl()); break;
366 case WAY: msg = tr("Fetching way with id {0} from ''{1}''", id, OsmApi.getOsmApi().getBaseUrl()); break;
367 case RELATION: msg = tr("Fetching relation with id {0} from ''{1}''", id, OsmApi.getOsmApi().getBaseUrl()); break;
368 }
369 progressMonitor.setCustomText(msg);
370 singleGetId(type, id, progressMonitor);
371 } catch(OsmApiException e) {
372 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
373 logger.warning(tr("Server replied with response code 404 for id {0}. Skipping.", Long.toString(id)));
374 missingPrimitives.add(id);
375 continue;
376 }
377 throw e;
378 }
379 }
380 }
381
382 /**
383 * merges the dataset <code>from</code> to {@see #outputDataSet}.
384 *
385 * @param from the other dataset
386 *
387 */
388 protected void merge(DataSet from) {
389 final DataSetMerger visitor = new DataSetMerger(outputDataSet,from);
390 visitor.merge();
391 }
392
393 /**
394 * fetches a set of ids of a given {@see OsmPrimitiveType} from the server
395 *
396 * @param ids the set of ids
397 * @param type the type
398 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
399 */
400 protected void fetchPrimitives(Set<Long> ids, OsmPrimitiveType type, ProgressMonitor progressMonitor) throws OsmTransferException{
401 String msg = "";
402 switch(type) {
403 case NODE: msg = tr("Fetching a package of nodes from ''{0}''", OsmApi.getOsmApi().getBaseUrl()); break;
404 case WAY: msg = tr("Fetching a package of ways from ''{0}''", OsmApi.getOsmApi().getBaseUrl()); break;
405 case RELATION: msg = tr("Fetching a package of relations from ''{0}''", OsmApi.getOsmApi().getBaseUrl()); break;
406 }
407 progressMonitor.setCustomText(msg);
408 Set<Long> toFetch = new HashSet<Long>(ids);
409 toFetch.addAll(ids);
410 while(! toFetch.isEmpty() && !isCanceled()) {
411 Set<Long> pkg = extractIdPackage(toFetch);
412 try {
413 multiGetIdPackage(type, pkg, progressMonitor);
414 } catch(OsmApiException e) {
415 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
416 logger.warning(tr("Server replied with response code 404, retrying with an individual request for each primitive."));
417 singleGetIdPackage(type, pkg, progressMonitor);
418 } else
419 throw e;
420 }
421 }
422 }
423
424 /**
425 * invokes one or more Multi Gets to fetch the {@see OsmPrimitive}s and replies
426 * the dataset of retrieved primitives. Note that the dataset includes non visible primitives too!
427 * In contrast to a simple Get for a node, a way, or a relation, a Multi Get always replies
428 * the latest version of the primitive (if any), even if the primitive is not visible (i.e. if
429 * visible==false).
430 *
431 * Invoke {@see #getMissingPrimitives()} to get a list of primitives which have not been
432 * found on the server (the server response code was 404)
433 *
434 * Invoke {@see #getSkippedWay()} to get a list of ways which this reader could not build from
435 * the fetched data because the ways refer to nodes which don't exist on the server.
436 *
437 * @return the parsed data
438 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
439 * @see #getMissingPrimitives()
440 * @see #getSkippedWays()
441 *
442
443 */
444 @Override
445 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
446 progressMonitor.beginTask("");
447 try {
448 missingPrimitives = new HashSet<Long>();
449 if (isCanceled())return null;
450 fetchPrimitives(nodes,OsmPrimitiveType.NODE, progressMonitor);
451 if (isCanceled())return null;
452 fetchPrimitives(ways,OsmPrimitiveType.WAY, progressMonitor);
453 if (isCanceled())return null;
454 fetchPrimitives(relations,OsmPrimitiveType.RELATION, progressMonitor);
455 return outputDataSet;
456 } finally {
457 progressMonitor.finishTask();
458 }
459 }
460
461 /**
462 * replies the set of ids of all primitives for which a fetch request to the
463 * server was submitted but which are not available from the server (the server
464 * replied a return code of 404)
465 *
466 * @return the set of ids of missing primitives
467 */
468 public Set<Long> getMissingPrimitives() {
469 return missingPrimitives;
470 }
471}
Note: See TracBrowser for help on using the repository browser.