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

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

new: MultiFetchServerObjectReader using APIs Multi Fetch method
update: now uses Multi Fetch to check for deleted primitives on the server
update: now uses Multi Fetch to update the selected primitives with the state from the server
fixed: cleaned up merging in MergeVisitor
new: conflict resolution dialog; now resolves conflicts due to different visibilities
new: replacement for realEqual() on OsmPrimitive and derived classes; realEqual now @deprecated
fixed: cleaning up OsmReader
fixed: progress indication in OsmApi

File size: 16.8 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.IOException;
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.Main;
17import org.openstreetmap.josm.data.osm.DataSet;
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.Relation;
22import org.openstreetmap.josm.data.osm.RelationMember;
23import org.openstreetmap.josm.data.osm.Way;
24import org.openstreetmap.josm.data.osm.visitor.MergeVisitor;
25import org.xml.sax.SAXException;
26
27/**
28 * Retrieves a set of {@see OsmPrimitive}s from an OSM server using the so called
29 * Multi Fetch API.
30 *
31 * Usage:
32 * <pre>
33 * MultiFetchServerObjectReader reader = MultiFetchServerObjectReader()
34 * .append(2345,2334,4444)
35 * .append(new Node(72343));
36 * reader.parseOsm();
37 * if (!reader.getMissingPrimitives().isEmpty()) {
38 * System.out.println("There are missing primitives: " + reader.getMissingPrimitives());
39 * }
40 * if (!reader.getSkippedWays().isEmpty()) {
41 * System.out.println("There are skipped ways: " + reader.getMissingPrimitives());
42 * }
43 * </pre>
44 *
45 *
46 */
47public class MultiFetchServerObjectReader extends OsmServerReader{
48
49 static private Logger logger = Logger.getLogger(MultiFetchServerObjectReader.class.getName());
50 /**
51 * the max. number of primitives retrieved in one step. Assuming IDs with 7 digits,
52 * this leads to a max. request URL of ~ 1600 Bytes ((7 digits + 1 Seperator) * 200),
53 * which should be safe according to the
54 * <a href="http://www.boutell.com/newfaq/misc/urllength.html">WWW FAQ</a>.
55 *
56 */
57 static private int MAX_IDS_PER_REQUEST = 200;
58
59
60 private HashSet<Long> nodes;
61 private HashSet<Long> ways;
62 private HashSet<Long> relations;
63 private HashSet<Long> missingPrimitives;
64 private HashSet<Long> skippedWayIds;
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 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.id == 0) return this;
171 remember(node.id, 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.id == 0) return this;
185 for (Node node: way.nodes) {
186 if (node.id > 0) {
187 remember(node.id, OsmPrimitiveType.NODE);
188 }
189 }
190 remember(way.id, 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.id == 0) return this;
204 remember(relation.id, OsmPrimitiveType.RELATION);
205 for (RelationMember member : relation.members) {
206 appendGeneric(member.member);
207 }
208 return this;
209 }
210
211
212 protected MultiFetchServerObjectReader appendGeneric(OsmPrimitive primitive) {
213 if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.NODE))
214 return append((Node)primitive);
215 else if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.WAY))
216 return append((Way)primitive);
217 else if (OsmPrimitiveType.from(primitive).equals(OsmPrimitiveType.RELATION))
218 return append((Relation)primitive);
219
220 return this;
221 }
222
223 /**
224 * appends a list of {@see OsmPrimitive} to the list of ids which will be fetched from the server.
225 *
226 * @param primitives the list of primitives (ignored, if null)
227 * @return this
228 *
229 * @see #append(Node)
230 * @see #append(Way)
231 * @see #append(Relation)
232 *
233 */
234 public MultiFetchServerObjectReader append(Collection<OsmPrimitive> primitives) {
235 if (primitives == null) return this;
236 for (OsmPrimitive primitive : primitives) {
237 appendGeneric(primitive);
238 }
239 return this;
240 }
241
242 /**
243 * extracts a subset of max {@see #MAX_IDS_PER_REQUEST} ids from <code>ids</code> and
244 * replies the subset. The extracted subset is removed from <code>ids</code>.
245 *
246 * @param ids a set of ids
247 * @return the subset of ids
248 */
249 protected Set<Long> extractIdPackage(Set<Long> ids) {
250 HashSet<Long> pkg = new HashSet<Long>();
251 if (ids.isEmpty())
252 return pkg;
253 if (ids.size() > MAX_IDS_PER_REQUEST) {
254 Iterator<Long> it = ids.iterator();
255 for (int i =0;i<MAX_IDS_PER_REQUEST;i++) {
256 pkg.add(it.next());
257 }
258 ids.removeAll(pkg);
259 } else {
260 pkg.addAll(ids);
261 ids.clear();
262 }
263 return pkg;
264 }
265
266
267 /**
268 * builds the Multi Get request string for a set of ids and a given
269 * {@see OsmPrimitiveType}.
270 *
271 * @param type the type
272 * @param idPackage the package of ids
273 * @return the request string
274 */
275 protected String buildRequestString(OsmPrimitiveType type, Set<Long> idPackage) {
276 StringBuilder sb = new StringBuilder();
277 sb.append(type.getAPIName()).append("s?")
278 .append(type.getAPIName()).append("s=");
279
280 Iterator<Long> it = idPackage.iterator();
281 for (int i=0; i< idPackage.size();i++) {
282 sb.append(it.next());
283 if (i < idPackage.size()-1) {
284 sb.append(",");
285 }
286 }
287 return sb.toString();
288 }
289
290 /**
291 * builds the Multi Get request string for a single id and a given
292 * {@see OsmPrimitiveType}.
293 *
294 * @param type the type
295 * @param id the id
296 * @return the request string
297 */
298 protected String buildRequestString(OsmPrimitiveType type, long id) {
299 StringBuilder sb = new StringBuilder();
300 sb.append(type.getAPIName()).append("s?")
301 .append(type.getAPIName()).append("s=")
302 .append(id);
303 return sb.toString();
304 }
305
306 /**
307 * invokes a Multi Get for a set of ids and a given {@see OsmPrimitiveType}.
308 * The retrieved primitives are merged to {@see #outputDataSet}.
309 *
310 * @param type the type
311 * @param pkg the package of ids
312 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
313 *
314 */
315 protected void multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg) throws OsmTransferException {
316 String request = buildRequestString(type, pkg);
317 final InputStream in = getInputStream(request, Main.pleaseWaitDlg);
318 if (in == null) return;
319 Main.pleaseWaitDlg.currentAction.setText(tr("Downloading OSM data..."));
320 try {
321 final OsmReader osm = OsmReader.parseDataSetOsm(in, outputDataSet, Main.pleaseWaitDlg);
322 skippedWayIds.addAll(osm.getSkippedWayIds());
323 merge(osm.getDs());
324 } catch(IOException e) {
325 throw new OsmTransferException(e);
326 } catch(SAXException e) {
327 throw new OsmTransferException(e);
328 }
329 }
330
331 /**
332 * invokes a Multi Get for a single id and a given {@see OsmPrimitiveType}.
333 * The retrieved primitive is merged to {@see #outputDataSet}.
334 *
335 * @param type the type
336 * @param id the id
337 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
338 *
339 */
340 protected void singleGetId(OsmPrimitiveType type, long id) throws OsmTransferException {
341 String request = buildRequestString(type, id);
342 final InputStream in = getInputStream(request, Main.pleaseWaitDlg);
343 if (in == null)
344 return;
345 Main.pleaseWaitDlg.currentAction.setText(tr("Downloading OSM data..."));
346 try {
347 final OsmReader osm = OsmReader.parseDataSetOsm(in, null, Main.pleaseWaitDlg);
348 skippedWayIds.addAll(osm.getSkippedWayIds());
349 merge(osm.getDs());
350 } catch(IOException e) {
351 throw new OsmTransferException(e);
352 } catch(SAXException 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) throws OsmTransferException {
371 for (long id : pkg) {
372 try {
373 singleGetId(type, id);
374 } catch(OsmApiException e) {
375 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
376 logger.warning(tr("Server replied with response code 404 for id {0}. Skipping.", Long.toString(id)));
377 missingPrimitives.add(id);
378 continue;
379 }
380 throw e;
381 }
382 }
383 }
384
385 /**
386 * merges the dataset <code>from</code> to {@see #outputDataSet}.
387 *
388 * @param from the other dataset
389 *
390 */
391 protected void merge(DataSet from) {
392 final MergeVisitor visitor = new MergeVisitor(outputDataSet,from);
393 visitor.merge();
394 }
395
396 /**
397 * fetches a set of ids of a given {@see OsmPrimitiveType} from the server
398 *
399 * @param ids the set of ids
400 * @param type the type
401 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
402 */
403 protected void fetchPrimitives(Set<Long> ids, OsmPrimitiveType type) throws OsmTransferException{
404 Set<Long> toFetch = new HashSet<Long>(ids);
405 toFetch.addAll(ids);
406 while(! toFetch.isEmpty()) {
407 Set<Long> pkg = extractIdPackage(toFetch);
408 try {
409 multiGetIdPackage(type, pkg);
410 } catch(OsmApiException e) {
411 if (e.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
412 logger.warning(tr("Server replied with response code 404, retrying with an individual request for each primitive"));
413 singleGetIdPackage(type, pkg);
414 } else
415 throw e;
416 }
417 }
418 }
419
420 /**
421 * invokes one or more Multi Gets to fetch the {@see OsmPrimitive}s and replies
422 * the dataset of retrieved primitives. Note that the dataset includes non visible primitives too!
423 * In contrast to a simple Get for a node, a way, or a relation, a Multi Get always replies
424 * the latest version of the primitive (if any), even if the primitive is not visible (i.e. if
425 * visible==false).
426 *
427 * Invoke {@see #getMissingPrimitives()} to get a list of primitives which have not been
428 * found on the server (the server response code was 404)
429 *
430 * Invoke {@see #getSkippedWay()} to get a list of ways which this reader could not build from
431 * the fetched data because the ways refer to nodes which don't exist on the server.
432 *
433 * @return the parsed data
434 * @exception OsmTransferException thrown if an error occurs while communicating with the API server
435 * @see #getMissingPrimitives()
436 * @see #getSkippedWays()
437 *
438
439 */
440 @Override
441 public DataSet parseOsm() throws OsmTransferException {
442 skippedWayIds = new HashSet<Long>();
443 missingPrimitives = new HashSet<Long>();
444
445 fetchPrimitives(nodes,OsmPrimitiveType.NODE);
446 fetchPrimitives(ways,OsmPrimitiveType.WAY);
447 fetchPrimitives(relations,OsmPrimitiveType.RELATION);
448 return outputDataSet;
449 }
450
451 /**
452 * replies the set of {@see Way}s which were present in the data fetched from the
453 * server but which were not included in the JOSM dataset because they referred
454 * to nodes not present in the dataset
455 *
456 * @return the set of ids of skipped ways
457 */
458 public Set<Long> getSkippedWays() {
459 return skippedWayIds;
460 }
461
462 /**
463 * replies the set of ids of all primitives for which a fetch request to the
464 * server was submitted but which are not available from the server (the server
465 * replied a return code of 404)
466 *
467 * @return the set of ids of missing primitives
468 */
469 public Set<Long> getMissingPrimitives() {
470 return missingPrimitives;
471 }
472}
Note: See TracBrowser for help on using the repository browser.