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

Last change on this file since 4067 was 3791, checked in by Upliner, 13 years ago

fix loading of invisible objects which was broken in [3731]

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