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

Last change on this file since 3423 was 3362, checked in by stoecker, 14 years ago

fix #5182 - Conflict system simplification - patch by Upliner

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