source: josm/trunk/src/org/openstreetmap/josm/io/OsmReader.java@ 2469

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

fixed #3976: Loading of 0.5 data floods with warnings

  • Property svn:eol-style set to native
File size: 24.0 KB
Line 
1package org.openstreetmap.josm.io;
2
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.io.InputStream;
6import java.io.InputStreamReader;
7import java.util.ArrayList;
8import java.util.Collection;
9import java.util.Date;
10import java.util.HashMap;
11import java.util.LinkedList;
12import java.util.List;
13import java.util.Map;
14import java.util.logging.Logger;
15
16import javax.xml.parsers.ParserConfigurationException;
17import javax.xml.parsers.SAXParserFactory;
18
19import org.openstreetmap.josm.data.Bounds;
20import org.openstreetmap.josm.data.coor.LatLon;
21import org.openstreetmap.josm.data.osm.DataSet;
22import org.openstreetmap.josm.data.osm.DataSource;
23import org.openstreetmap.josm.data.osm.Node;
24import org.openstreetmap.josm.data.osm.OsmPrimitive;
25import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
26import org.openstreetmap.josm.data.osm.Relation;
27import org.openstreetmap.josm.data.osm.RelationMember;
28import org.openstreetmap.josm.data.osm.User;
29import org.openstreetmap.josm.data.osm.Way;
30import org.openstreetmap.josm.gui.progress.ProgressMonitor;
31import org.openstreetmap.josm.tools.DateUtils;
32import org.xml.sax.Attributes;
33import org.xml.sax.InputSource;
34import org.xml.sax.Locator;
35import org.xml.sax.SAXException;
36import org.xml.sax.helpers.DefaultHandler;
37
38/**
39 * Parser for the Osm Api. Read from an input stream and construct a dataset out of it.
40 *
41 */
42public class OsmReader {
43 static private final Logger logger = Logger.getLogger(OsmReader.class.getName());
44
45 /**
46 * The dataset to add parsed objects to.
47 */
48 private DataSet ds = new DataSet();
49
50 /**
51 * Replies the parsed data set
52 *
53 * @return the parsed data set
54 */
55 public DataSet getDataSet() {
56 return ds;
57 }
58
59 /** the map from external ids to read OsmPrimitives. External ids are
60 * longs too, but in contrast to internal ids negative values are used
61 * to identify primitives unknown to the OSM server
62 *
63 * The keys are strings composed as follows
64 * <ul>
65 * <li>"n" + id for nodes</li>
66 * <li>"w" + id for nodes</li>
67 * <li>"r" + id for nodes</li>
68 * </ul>
69 */
70 private Map<String, OsmPrimitive> externalIdMap = new HashMap<String, OsmPrimitive>();
71
72
73 /**
74 * constructor (for private use only)
75 *
76 * @see #parseDataSet(InputStream, DataSet, ProgressMonitor)
77 * @see #parseDataSetOsm(InputStream, DataSet, ProgressMonitor)
78 */
79 private OsmReader() {
80 externalIdMap = new HashMap<String, OsmPrimitive>();
81 }
82
83 private static class OsmPrimitiveData {
84 public long id = 0;
85 public boolean modified = false;
86 public boolean deleted = false;
87 public Date timestamp = new Date();
88 public User user = null;
89 public boolean visible = true;
90 public int version = 0;
91 public LatLon latlon = new LatLon(0,0);
92 private OsmPrimitive primitive;
93
94 public void copyTo(OsmPrimitive osm) {
95 // It's not necessary to call clearOsmId for id < 0. The same thing is done by parameterless constructor
96 if (id > 0) {
97 osm.setOsmId(id, version);
98 }
99 osm.setDeleted(deleted);
100 osm.setModified(modified | deleted);
101 osm.setTimestamp(timestamp);
102 osm.setUser(user);
103 osm.setVisible(visible);
104 osm.mappaintStyle = null;
105 }
106
107 public Node createNode() {
108 Node node = new Node();
109 node.setCoor(latlon);
110 copyTo(node);
111 primitive = node;
112 return node;
113 }
114
115 public Way createWay() {
116 Way way = new Way();
117 copyTo(way);
118 primitive = way;
119 return way;
120 }
121 public Relation createRelation() {
122 Relation relation= new Relation();
123 copyTo(relation);
124 primitive = relation;
125 return relation;
126 }
127
128 public void rememberTag(String key, String value) {
129 primitive.put(key, value);
130 }
131 }
132
133 /**
134 * Used as a temporary storage for relation members, before they
135 * are resolved into pointers to real objects.
136 */
137 private static class RelationMemberData {
138 public String type;
139 public long id;
140 public String role;
141 }
142
143 /**
144 * Data structure for the remaining way objects
145 */
146 private Map<Long, Collection<Long>> ways = new HashMap<Long, Collection<Long>>();
147
148 /**
149 * Data structure for relation objects
150 */
151 private Map<Long, Collection<RelationMemberData>> relations = new HashMap<Long, Collection<RelationMemberData>>();
152
153 private class Parser extends DefaultHandler {
154 private Locator locator;
155
156 @Override
157 public void setDocumentLocator(Locator locator) {
158 this.locator = locator;
159 }
160
161 protected void throwException(String msg) throws OsmDataParsingException{
162 throw new OsmDataParsingException(msg).rememberLocation(locator);
163 }
164 /**
165 * The current osm primitive to be read.
166 */
167 private OsmPrimitiveData current;
168 private String generator;
169
170
171 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
172 if (qName.equals("osm")) {
173 if (atts == null) {
174 throwException(tr("Missing mandatory attribute ''{0}'' of XML element {1}.", "version", "osm"));
175 }
176 String v = atts.getValue("version");
177 if (v == null) {
178 throwException(tr("Missing mandatory attribute ''{0}''.", "version"));
179 }
180 if (!(v.equals("0.5") || v.equals("0.6"))) {
181 throwException(tr("Unsupported version: {0}", v));
182 }
183 // save generator attribute for later use when creating DataSource objects
184 generator = atts.getValue("generator");
185 ds.setVersion(v);
186
187 } else if (qName.equals("bounds")) {
188 // new style bounds.
189 String minlon = atts.getValue("minlon");
190 String minlat = atts.getValue("minlat");
191 String maxlon = atts.getValue("maxlon");
192 String maxlat = atts.getValue("maxlat");
193 String origin = atts.getValue("origin");
194 if (minlon != null && maxlon != null && minlat != null && maxlat != null) {
195 if (origin == null) {
196 origin = generator;
197 }
198 Bounds bounds = new Bounds(
199 new LatLon(Double.parseDouble(minlat), Double.parseDouble(minlon)),
200 new LatLon(Double.parseDouble(maxlat), Double.parseDouble(maxlon)));
201 DataSource src = new DataSource(bounds, origin);
202 ds.dataSources.add(src);
203 } else {
204 throwException(tr(
205 "Missing manadatory attributes on element ''bounds''. Got minlon=''{0}'',minlat=''{1}'',maxlon=''{3}'',maxlat=''{4}'', origin=''{5}''.",
206 minlon, minlat, maxlon, maxlat, origin
207 ));
208 }
209
210 // ---- PARSING NODES AND WAYS ----
211
212 } else if (qName.equals("node")) {
213 current = new OsmPrimitiveData();
214 current.latlon = new LatLon(getDouble(atts, "lat"), getDouble(atts, "lon"));
215 readCommon(atts, current);
216 Node n = current.createNode();
217 externalIdMap.put("n"+current.id, n);
218 } else if (qName.equals("way")) {
219 current = new OsmPrimitiveData();
220 readCommon(atts, current);
221 Way w = current.createWay();
222 externalIdMap.put("w"+current.id, w);
223 ways.put(current.id, new ArrayList<Long>());
224 } else if (qName.equals("nd")) {
225 Collection<Long> list = ways.get(current.id);
226 if (list == null) {
227 throwException(
228 tr("Found XML element <nd> not as direct child of element <way>.")
229 );
230 }
231 if (atts.getValue("ref") == null) {
232 throwException(
233 tr("Missing mandatory attribute ''{0}'' on <nd> of way {1}.", "ref", current.id)
234 );
235 }
236 long id = getLong(atts, "ref");
237 if (id == 0) {
238 throwException(
239 tr("Illegal value of attribute ''ref'' of element <nd>. Got {0}.", id)
240 );
241 }
242 list.add(id);
243
244 // ---- PARSING RELATIONS ----
245
246 } else if (qName.equals("relation")) {
247 current = new OsmPrimitiveData();
248 readCommon(atts, current);
249 Relation r = current.createRelation();
250 externalIdMap.put("r"+current.id, r );
251 relations.put(current.id, new LinkedList<RelationMemberData>());
252 } else if (qName.equals("member")) {
253 Collection<RelationMemberData> list = relations.get(current.id);
254 if (list == null) {
255 throwException(
256 tr("Found XML element <member> not as direct child of element <relation>.")
257 );
258 }
259 RelationMemberData emd = new RelationMemberData();
260 String value = atts.getValue("ref");
261 if (value == null) {
262 throwException(tr("Missing attribute ''ref'' on member in relation {0}.",current.id));
263 }
264 try {
265 emd.id = Long.parseLong(value);
266 } catch(NumberFormatException e) {
267 throwException(tr("Illegal value for attribute ''ref'' on member in relation {0}. Got {1}", Long.toString(current.id),value));
268 }
269 value = atts.getValue("type");
270 if (value == null) {
271 throwException(tr("Missing attribute ''type'' on member {0} in relation {1}.", Long.toString(emd.id), Long.toString(current.id)));
272 }
273 if (! (value.equals("way") || value.equals("node") || value.equals("relation"))) {
274 throwException(tr("Illegal value for attribute ''type'' on member {0} in relation {1}. Got {2}.", Long.toString(emd.id), Long.toString(current.id), value));
275 }
276 emd.type= value;
277 value = atts.getValue("role");
278 emd.role = value;
279
280 if (emd.id == 0) {
281 throwException(tr("Incomplete <member> specification with ref=0"));
282 }
283
284 list.add(emd);
285
286 // ---- PARSING TAGS (applicable to all objects) ----
287
288 } else if (qName.equals("tag")) {
289 String key = atts.getValue("k");
290 String value = atts.getValue("v");
291 current.rememberTag(key, value);
292 } else {
293 System.out.println(tr("Undefined element ''{0}'' found in input stream. Skipping.", qName));
294 }
295 }
296
297 private double getDouble(Attributes atts, String value) {
298 return Double.parseDouble(atts.getValue(value));
299 }
300
301 private User createUser(String uid, String name) throws SAXException {
302 if (uid == null) {
303 if (name == null)
304 return null;
305 return User.createLocalUser(name);
306 }
307 try {
308 long id = Long.parseLong(uid);
309 return User.createOsmUser(id, name);
310 } catch(NumberFormatException e) {
311 throwException(tr("Illegal value for attribute ''uid''. Got ''{0}''.", uid));
312 }
313 return null;
314 }
315 /**
316 * Read out the common attributes from atts and put them into this.current.
317 */
318 void readCommon(Attributes atts, OsmPrimitiveData current) throws SAXException {
319 current.id = getLong(atts, "id");
320 if (current.id == 0) {
321 throwException(tr("Illegal object with ID=0."));
322 }
323
324 String time = atts.getValue("timestamp");
325 if (time != null && time.length() != 0) {
326 current.timestamp = DateUtils.fromString(time);
327 }
328
329 // user attribute added in 0.4 API
330 String user = atts.getValue("user");
331 // uid attribute added in 0.6 API
332 String uid = atts.getValue("uid");
333 current.user = createUser(uid, user);
334
335 // visible attribute added in 0.4 API
336 String visible = atts.getValue("visible");
337 if (visible != null) {
338 current.visible = Boolean.parseBoolean(visible);
339 }
340
341 String version = atts.getValue("version");
342 current.version = 0;
343 if (version != null) {
344 try {
345 current.version = Integer.parseInt(version);
346 } catch(NumberFormatException e) {
347 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.", Long.toString(current.id), version));
348 }
349 if (ds.getVersion().equals("0.6")){
350 if (current.version <= 0 && current.id > 0) {
351 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.", Long.toString(current.id), version));
352 } else if (current.version < 0 && current.id <=0) {
353 System.out.println(tr("WARNING: Normalizing value of attribute ''version'' of element {0} to {2}, API version is ''{3}''. Got {1}.", current.id, current.version, 0, "0.6"));
354 current.version = 0;
355 }
356 } else if (ds.getVersion().equals("0.5")) {
357 if (current.version <= 0 && current.id > 0) {
358 System.out.println(tr("WARNING: Normalizing value of attribute ''version'' of element {0} to {2}, API version is ''{3}''. Got {1}.", current.id, current.version, 1, "0.5"));
359 current.version = 1;
360 } else if (current.version < 0 && current.id <=0) {
361 System.out.println(tr("WARNING: Normalizing value of attribute ''version'' of element {0} to {2}, API version is ''{3}''. Got {1}.", current.id, current.version, 0, "0.5"));
362 current.version = 0;
363 }
364 } else {
365 // should not happen. API version has been checked before
366 throwException(tr("Unknown or unsupported API version. Got {0}.", ds.getVersion()));
367 }
368 } else {
369 // version expected for OSM primitives with an id assigned by the server (id > 0), since API 0.6
370 //
371 if (current.id > 0 && ds.getVersion() != null && ds.getVersion().equals("0.6")) {
372 throwException(tr("Missing attribute ''version'' on OSM primitive with ID {0}.", Long.toString(current.id)));
373 } else if (current.id > 0 && ds.getVersion() != null && ds.getVersion().equals("0.5")) {
374 // default version in 0.5 files for existing primitives
375 System.out.println(tr("WARNING: Normalizing value of attribute ''version'' of element {0} to {2}, API version is ''{3}''. Got {1}.", current.id, current.version, 1, "0.5"));
376 current.version= 1;
377 } else if (current.id <= 0 && ds.getVersion() != null && ds.getVersion().equals("0.5")) {
378 // default version in 0.5 files for new primitives, no warning necessary. This is
379 // (was) legal in API 0.5
380 current.version= 0;
381 }
382 }
383
384 String action = atts.getValue("action");
385 if (action == null)
386 return;
387 if (action.equals("delete")) {
388 current.deleted = true;
389 } else if (action.startsWith("modify")) {
390 current.modified = true;
391 }
392 }
393
394 private long getLong(Attributes atts, String name) throws SAXException {
395 String value = atts.getValue(name);
396 if (value == null) {
397 throwException(tr("Missing required attribute ''{0}''.",name));
398 }
399 try {
400 return Long.parseLong(value);
401 } catch(NumberFormatException e) {
402 throwException(tr("Illegal long value for attribute ''{0}''. Got ''{1}''.",name, value));
403 }
404 return 0; // should not happen
405 }
406 }
407
408
409 /**
410 * Processes the ways after parsing. Rebuilds the list of nodes of each way and
411 * adds the way to the dataset
412 *
413 * @throws IllegalDataException thrown if a data integrity problem is detected
414 */
415 protected void processWaysAfterParsing() throws IllegalDataException{
416 for (Long externalWayId: ways.keySet()) {
417 Way w = (Way)externalIdMap.get("w" + externalWayId);
418 boolean incomplete = false;
419 List<Node> wayNodes = new ArrayList<Node>();
420 for (long id : ways.get(externalWayId)) {
421 Node n = (Node)externalIdMap.get("n" +id);
422 if (n == null) {
423 if (id <= 0)
424 throw new IllegalDataException (
425 tr(
426 "Way with external ID ''{0}'' includes missing node with external ID ''{1}''.",
427 externalWayId,
428 id
429 )
430 );
431 // create an incomplete node if necessary
432 //
433 n = (Node)ds.getPrimitiveById(id,OsmPrimitiveType.NODE);
434 if (n == null) {
435 n = new Node(id);
436 n.incomplete = true;
437 ds.addPrimitive(n);
438 }
439 incomplete = true;
440 }
441 wayNodes.add(n);
442 }
443 w.setNodes(wayNodes);
444 if (incomplete) {
445 logger.warning(tr("Marked way {0} with {1} nodes incomplete because at least one node was missing in the " +
446 "loaded data and is therefore incomplete too.", externalWayId, w.getNodesCount()));
447 w.incomplete = true;
448 ds.addPrimitive(w);
449 } else {
450 w.incomplete = false;
451 ds.addPrimitive(w);
452 }
453 }
454 }
455
456 /**
457 * Processes the parsed nodes after parsing. Just adds them to
458 * the dataset
459 *
460 */
461 protected void processNodesAfterParsing() {
462 for (OsmPrimitive primitive: externalIdMap.values()) {
463 if (primitive instanceof Node) {
464 this.ds.addPrimitive(primitive);
465 }
466 }
467 }
468
469 /**
470 * Completes the parsed relations with its members.
471 *
472 * @throws IllegalDataException thrown if a data integrity problem is detected, i.e. if a
473 * relation member refers to a local primitive which wasn't available in the data
474 *
475 */
476 private void processRelationsAfterParsing() throws IllegalDataException {
477 for (Long externalRelationId : relations.keySet()) {
478 Relation relation = (Relation) externalIdMap.get("r" +externalRelationId);
479 List<RelationMember> relationMembers = new ArrayList<RelationMember>();
480 for (RelationMemberData rm : relations.get(externalRelationId)) {
481 OsmPrimitive primitive = null;
482
483 // lookup the member from the map of already created primitives
484 //
485 if (rm.type.equals("node")) {
486 primitive = externalIdMap.get("n" + rm.id);
487 } else if (rm.type.equals("way")) {
488 primitive = externalIdMap.get("w" + rm.id);
489 } else if (rm.type.equals("relation")) {
490 primitive = externalIdMap.get("r" + rm.id);
491 } else
492 throw new IllegalDataException(
493 tr("Unknown relation member type ''{0}'' in relation with external id ''{1}''.", rm.type,externalRelationId)
494 );
495
496 if (primitive == null) {
497 if (rm.id <= 0)
498 // relation member refers to a primitive with a negative id which was not
499 // found in the data. This is always a data integrity problem and we abort
500 // with an exception
501 //
502 throw new IllegalDataException(
503 tr(
504 "Relation with external id ''{0}'' refers to a missing primitive with external id ''{1}''.",
505 externalRelationId,
506 rm.id
507 )
508 );
509
510 // member refers to OSM primitive which was not present in the parsed data
511 // -> create a new incomplete primitive and add it to the dataset
512 //
513 if (rm.type.equals("node")) {
514 primitive = new Node(rm.id);
515 } else if (rm.type.equals("way")) {
516 primitive = new Way(rm.id);
517 } else if (rm.type.equals("relation")) {
518 primitive = new Relation(rm.id);
519 } else {
520 // can't happen, we've been testing for valid member types
521 // at the beginning of this method
522 //
523 }
524 ds.addPrimitive(primitive);
525
526 if (rm.type.equals("node")) {
527 externalIdMap.put("n" + rm.id, primitive);
528 } else if (rm.type.equals("way")) {
529 externalIdMap.put("w" + rm.id, primitive);
530 } else if (rm.type.equals("relation")) {
531 externalIdMap.put("r" + rm.id, primitive);
532 }
533
534 }
535 relationMembers.add(new RelationMember(rm.role, primitive));
536 }
537 relation.setMembers(relationMembers);
538 ds.addPrimitive(relation);
539 }
540 }
541
542 /**
543 * Parse the given input source and return the dataset.
544 *
545 * @param source the source input stream
546 * @param progressMonitor the progress monitor
547 *
548 * @return the dataset with the parsed data
549 * @throws IllegalDataException thrown if the an error was found while parsing the data from the source
550 */
551 public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
552 OsmReader reader = new OsmReader();
553 try {
554 progressMonitor.beginTask(tr("Prepare OSM data...", 2));
555 progressMonitor.subTask(tr("Parsing OSM data..."));
556 InputSource inputSource = new InputSource(new InputStreamReader(source, "UTF-8"));
557 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, reader.new Parser());
558 progressMonitor.worked(1);
559
560 progressMonitor.subTask(tr("Preparing data set..."));
561 reader.processNodesAfterParsing();
562 reader.processWaysAfterParsing();
563 reader.processRelationsAfterParsing();
564 progressMonitor.worked(1);
565 return reader.getDataSet();
566 } catch(IllegalDataException e) {
567 throw e;
568 } catch(ParserConfigurationException e) {
569 throw new IllegalDataException(e.getMessage(), e);
570 } catch(SAXException e) {
571 throw new IllegalDataException(e.getMessage(), e);
572 } catch(Exception e) {
573 throw new IllegalDataException(e);
574 } finally {
575 progressMonitor.finishTask();
576 }
577 }
578}
Note: See TracBrowser for help on using the repository browser.