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

Last change on this file since 3566 was 3479, checked in by jttt, 14 years ago

cosmetics

  • Property svn:eol-style set to native
File size: 26.8 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.load(nd);
172 externalIdMap.put(nd.getPrimitiveId(), n);
173 currentPrimitive = n;
174 currentExternalId = nd.getUniqueId();
175 } else if (qName.equals("way")) {
176 WayData wd = new WayData();
177 readCommon(atts, wd);
178 Way w = new Way(wd.getId(), wd.getVersion());
179 w.load(wd);
180 externalIdMap.put(wd.getPrimitiveId(), w);
181 ways.put(wd.getUniqueId(), new ArrayList<Long>());
182 currentPrimitive = w;
183 currentExternalId = wd.getUniqueId();
184 } else if (qName.equals("nd")) {
185 Collection<Long> list = ways.get(currentExternalId);
186 if (list == null) {
187 throwException(
188 tr("Found XML element <nd> not as direct child of element <way>.")
189 );
190 }
191 if (atts.getValue("ref") == null) {
192 throwException(
193 tr("Missing mandatory attribute ''{0}'' on <nd> of way {1}.", "ref", currentPrimitive.getUniqueId())
194 );
195 }
196 long id = getLong(atts, "ref");
197 if (id == 0) {
198 throwException(
199 tr("Illegal value of attribute ''ref'' of element <nd>. Got {0}.", id)
200 );
201 }
202 if (currentPrimitive.isDeleted()) {
203 logger.info(tr("Deleted way {0} contains nodes", currentPrimitive.getUniqueId()));
204 } else {
205 list.add(id);
206 }
207
208 // ---- PARSING RELATIONS ----
209
210 } else if (qName.equals("relation")) {
211 RelationData rd = new RelationData();
212 readCommon(atts, rd);
213 Relation r = new Relation(rd.getId(), rd.getVersion());
214 r.load(rd);
215 externalIdMap.put(rd.getPrimitiveId(), r);
216 relations.put(rd.getUniqueId(), new LinkedList<RelationMemberData>());
217 currentPrimitive = r;
218 currentExternalId = rd.getUniqueId();
219 } else if (qName.equals("member")) {
220 Collection<RelationMemberData> list = relations.get(currentExternalId);
221 if (list == null) {
222 throwException(
223 tr("Found XML element <member> not as direct child of element <relation>.")
224 );
225 }
226 RelationMemberData emd = new RelationMemberData();
227 String value = atts.getValue("ref");
228 if (value == null) {
229 throwException(tr("Missing attribute ''ref'' on member in relation {0}.",currentPrimitive.getUniqueId()));
230 }
231 try {
232 emd.id = Long.parseLong(value);
233 } catch(NumberFormatException e) {
234 throwException(tr("Illegal value for attribute ''ref'' on member in relation {0}. Got {1}", Long.toString(currentPrimitive.getUniqueId()),value));
235 }
236 value = atts.getValue("type");
237 if (value == null) {
238 throwException(tr("Missing attribute ''type'' on member {0} in relation {1}.", Long.toString(emd.id), Long.toString(currentPrimitive.getUniqueId())));
239 }
240 try {
241 emd.type = OsmPrimitiveType.fromApiTypeName(value);
242 } catch(IllegalArgumentException e) {
243 throwException(tr("Illegal value for attribute ''type'' on member {0} in relation {1}. Got {2}.", Long.toString(emd.id), Long.toString(currentPrimitive.getUniqueId()), value));
244 }
245 value = atts.getValue("role");
246 emd.role = value;
247
248 if (emd.id == 0) {
249 throwException(tr("Incomplete <member> specification with ref=0"));
250 }
251
252 if (currentPrimitive.isDeleted()) {
253 logger.info(tr("Deleted relation {0} contains members", currentPrimitive.getUniqueId()));
254 } else {
255 list.add(emd);
256 }
257
258 // ---- PARSING TAGS (applicable to all objects) ----
259
260 } else if (qName.equals("tag")) {
261 String key = atts.getValue("k");
262 String value = atts.getValue("v");
263 if (key == null || value == null) {
264 throwException(tr("Missing key or value attribute in tag."));
265 }
266 currentPrimitive.put(key.intern(), value.intern());
267
268 } else {
269 System.out.println(tr("Undefined element ''{0}'' found in input stream. Skipping.", qName));
270 }
271 } catch (Exception e) {
272 throw new SAXParseException(e.getMessage(), locator, e);
273 }
274 }
275
276 private double getDouble(Attributes atts, String value) {
277 return Double.parseDouble(atts.getValue(value));
278 }
279
280 private User createUser(String uid, String name) throws SAXException {
281 if (uid == null) {
282 if (name == null)
283 return null;
284 return User.createLocalUser(name);
285 }
286 try {
287 long id = Long.parseLong(uid);
288 return User.createOsmUser(id, name);
289 } catch(NumberFormatException e) {
290 throwException(MessageFormat.format("Illegal value for attribute ''uid''. Got ''{0}''.", uid));
291 }
292 return null;
293 }
294 /**
295 * Read out the common attributes from atts and put them into this.current.
296 */
297 void readCommon(Attributes atts, PrimitiveData current) throws SAXException {
298 current.setId(getLong(atts, "id"));
299 if (current.getUniqueId() == 0) {
300 throwException(tr("Illegal object with ID=0."));
301 }
302
303 String time = atts.getValue("timestamp");
304 if (time != null && time.length() != 0) {
305 current.setTimestamp(DateUtils.fromString(time));
306 }
307
308 // user attribute added in 0.4 API
309 String user = atts.getValue("user");
310 // uid attribute added in 0.6 API
311 String uid = atts.getValue("uid");
312 current.setUser(createUser(uid, user));
313
314 // visible attribute added in 0.4 API
315 String visible = atts.getValue("visible");
316 if (visible != null) {
317 current.setVisible(Boolean.parseBoolean(visible));
318 }
319
320 String versionString = atts.getValue("version");
321 int version = 0;
322 if (versionString != null) {
323 try {
324 version = Integer.parseInt(versionString);
325 } catch(NumberFormatException e) {
326 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.", Long.toString(current.getUniqueId()), versionString));
327 }
328 if (ds.getVersion().equals("0.6")){
329 if (version <= 0 && current.getUniqueId() > 0) {
330 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.", Long.toString(current.getUniqueId()), versionString));
331 } else if (version < 0 && current.getUniqueId() <= 0) {
332 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"));
333 version = 0;
334 }
335 } else if (ds.getVersion().equals("0.5")) {
336 if (version <= 0 && current.getUniqueId() > 0) {
337 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"));
338 version = 1;
339 } else 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, 0, "0.5"));
341 version = 0;
342 }
343 } else {
344 // should not happen. API version has been checked before
345 throwException(tr("Unknown or unsupported API version. Got {0}.", ds.getVersion()));
346 }
347 } else {
348 // version expected for OSM primitives with an id assigned by the server (id > 0), since API 0.6
349 //
350 if (current.getUniqueId() > 0 && ds.getVersion() != null && ds.getVersion().equals("0.6")) {
351 throwException(tr("Missing attribute ''version'' on OSM primitive with ID {0}.", Long.toString(current.getUniqueId())));
352 } else if (current.getUniqueId() > 0 && ds.getVersion() != null && ds.getVersion().equals("0.5")) {
353 // default version in 0.5 files for existing primitives
354 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"));
355 version= 1;
356 } else if (current.getUniqueId() <= 0 && ds.getVersion() != null && ds.getVersion().equals("0.5")) {
357 // default version in 0.5 files for new primitives, no warning necessary. This is
358 // (was) legal in API 0.5
359 version= 0;
360 }
361 }
362 current.setVersion(version);
363
364 String action = atts.getValue("action");
365 if (action == null) {
366 // do nothing
367 } else if (action.equals("delete")) {
368 current.setDeleted(true);
369 current.setModified(current.isVisible());
370 } else if (action.equals("modify")) {
371 current.setModified(true);
372 }
373
374 String v = atts.getValue("changeset");
375 if (v == null) {
376 current.setChangesetId(0);
377 } else {
378 try {
379 current.setChangesetId(Integer.parseInt(v));
380 } catch(NumberFormatException e) {
381 if (current.getUniqueId() <= 0) {
382 // for a new primitive we just log a warning
383 System.out.println(tr("Illegal value for attribute ''changeset'' on new object {1}. Got {0}. Resetting to 0.", v, current.getUniqueId()));
384 current.setChangesetId(0);
385 } else {
386 // for an existing primitive this is a problem
387 throwException(tr("Illegal value for attribute ''changeset''. Got {0}.", v));
388 }
389 }
390 if (current.getChangesetId() <=0) {
391 if (current.getUniqueId() <= 0) {
392 // for a new primitive we just log a warning
393 System.out.println(tr("Illegal value for attribute ''changeset'' on new object {1}. Got {0}. Resetting to 0.", v, current.getUniqueId()));
394 current.setChangesetId(0);
395 } else {
396 // for an existing primitive this is a problem
397 throwException(tr("Illegal value for attribute ''changeset''. Got {0}.", v));
398 }
399 }
400 }
401 }
402
403 private long getLong(Attributes atts, String name) throws SAXException {
404 String value = atts.getValue(name);
405 if (value == null) {
406 throwException(tr("Missing required attribute ''{0}''.",name));
407 }
408 try {
409 return Long.parseLong(value);
410 } catch(NumberFormatException e) {
411 throwException(tr("Illegal long value for attribute ''{0}''. Got ''{1}''.",name, value));
412 }
413 return 0; // should not happen
414 }
415 }
416
417 /**
418 * Processes the ways after parsing. Rebuilds the list of nodes of each way and
419 * adds the way to the dataset
420 *
421 * @throws IllegalDataException thrown if a data integrity problem is detected
422 */
423 protected void processWaysAfterParsing() throws IllegalDataException{
424 for (Long externalWayId: ways.keySet()) {
425 Way w = (Way)externalIdMap.get(new SimplePrimitiveId(externalWayId, OsmPrimitiveType.WAY));
426 List<Node> wayNodes = new ArrayList<Node>();
427 for (long id : ways.get(externalWayId)) {
428 Node n = (Node)externalIdMap.get(new SimplePrimitiveId(id, OsmPrimitiveType.NODE));
429 if (n == null) {
430 if (id <= 0)
431 throw new IllegalDataException (
432 tr("Way with external ID ''{0}'' includes missing node with external ID ''{1}''.",
433 externalWayId,
434 id));
435 // create an incomplete node if necessary
436 //
437 n = (Node)ds.getPrimitiveById(id,OsmPrimitiveType.NODE);
438 if (n == null) {
439 n = new Node(id);
440 ds.addPrimitive(n);
441 }
442 }
443 if (n.isDeleted()) {
444 logger.warning(tr("Deleted node {0} is part of way {1}", id, w.getId()));
445 } else {
446 wayNodes.add(n);
447 }
448 }
449 w.setNodes(wayNodes);
450 if (w.hasIncompleteNodes()) {
451 if (logger.isLoggable(Level.FINE)) {
452 logger.fine(tr("Way {0} with {1} nodes has incomplete nodes because at least one node was missing in the loaded data.",
453 externalWayId, w.getNodesCount()));
454 }
455 }
456 ds.addPrimitive(w);
457 }
458 }
459
460 /**
461 * Processes the parsed nodes after parsing. Just adds them to
462 * the dataset
463 *
464 */
465 protected void processNodesAfterParsing() {
466 for (OsmPrimitive primitive: externalIdMap.values()) {
467 if (primitive instanceof Node) {
468 this.ds.addPrimitive(primitive);
469 }
470 }
471 }
472
473 /**
474 * Completes the parsed relations with its members.
475 *
476 * @throws IllegalDataException thrown if a data integrity problem is detected, i.e. if a
477 * relation member refers to a local primitive which wasn't available in the data
478 *
479 */
480 private void processRelationsAfterParsing() throws IllegalDataException {
481
482 // First add all relations to make sure that when relation reference other relation, the referenced will be already in dataset
483 for (Long externalRelationId : relations.keySet()) {
484 Relation relation = (Relation) externalIdMap.get(
485 new SimplePrimitiveId(externalRelationId, OsmPrimitiveType.RELATION)
486 );
487 ds.addPrimitive(relation);
488 }
489
490 for (Long externalRelationId : relations.keySet()) {
491 Relation relation = (Relation) externalIdMap.get(
492 new SimplePrimitiveId(externalRelationId, OsmPrimitiveType.RELATION)
493 );
494 List<RelationMember> relationMembers = new ArrayList<RelationMember>();
495 for (RelationMemberData rm : relations.get(externalRelationId)) {
496 OsmPrimitive primitive = null;
497
498 // lookup the member from the map of already created primitives
499 primitive = externalIdMap.get(new SimplePrimitiveId(rm.id, rm.type));
500
501 if (primitive == null) {
502 if (rm.id <= 0)
503 // relation member refers to a primitive with a negative id which was not
504 // found in the data. This is always a data integrity problem and we abort
505 // with an exception
506 //
507 throw new IllegalDataException(
508 tr("Relation with external id ''{0}'' refers to a missing primitive with external id ''{1}''.",
509 externalRelationId,
510 rm.id));
511
512 // member refers to OSM primitive which was not present in the parsed data
513 // -> create a new incomplete primitive and add it to the dataset
514 //
515 primitive = ds.getPrimitiveById(rm.id, rm.type);
516 if (primitive == null) {
517 switch (rm.type) {
518 case NODE:
519 primitive = new Node(rm.id); break;
520 case WAY:
521 primitive = new Way(rm.id); break;
522 case RELATION:
523 primitive = new Relation(rm.id); break;
524 default: throw new AssertionError(); // can't happen
525 }
526
527 ds.addPrimitive(primitive);
528 externalIdMap.put(new SimplePrimitiveId(rm.id, rm.type), primitive);
529 }
530 }
531 if (primitive.isDeleted()) {
532 logger.warning(tr("Deleted member {0} is used by relation {1}", primitive.getId(), relation.getId()));
533 } else {
534 relationMembers.add(new RelationMember(rm.role, primitive));
535 }
536 }
537 relation.setMembers(relationMembers);
538 }
539 }
540
541 /**
542 * Parse the given input source and return the dataset.
543 *
544 * @param source the source input stream. Must not be null.
545 * @param progressMonitor the progress monitor. If null, {@see NullProgressMonitor#INSTANCE} is assumed
546 *
547 * @return the dataset with the parsed data
548 * @throws IllegalDataException thrown if the an error was found while parsing the data from the source
549 * @throws IllegalArgumentException thrown if source is null
550 */
551 public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
552 if (progressMonitor == null) {
553 progressMonitor = NullProgressMonitor.INSTANCE;
554 }
555 CheckParameterUtil.ensureParameterNotNull(source, "source");
556 OsmReader reader = new OsmReader();
557 try {
558 progressMonitor.beginTask(tr("Prepare OSM data...", 2));
559 progressMonitor.indeterminateSubTask(tr("Parsing OSM data..."));
560
561 InputSource inputSource = new InputSource(UTFInputStreamReader.create(source, "UTF-8"));
562 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, reader.new Parser());
563 progressMonitor.worked(1);
564
565 progressMonitor.indeterminateSubTask(tr("Preparing data set..."));
566 reader.ds.beginUpdate();
567 try {
568 reader.processNodesAfterParsing();
569 reader.processWaysAfterParsing();
570 reader.processRelationsAfterParsing();
571 } finally {
572 reader.ds.endUpdate();
573 }
574 progressMonitor.worked(1);
575 return reader.getDataSet();
576 } catch(IllegalDataException e) {
577 throw e;
578 } catch(ParserConfigurationException e) {
579 throw new IllegalDataException(e.getMessage(), e);
580 } catch (SAXParseException e) {
581 throw new IllegalDataException(tr("Line {0} column {1}: ", e.getLineNumber(), e.getColumnNumber()) + e.getMessage(), e);
582 } catch(SAXException e) {
583 throw new IllegalDataException(e.getMessage(), e);
584 } catch(Exception e) {
585 throw new IllegalDataException(e);
586 } finally {
587 progressMonitor.finishTask();
588 }
589 }
590}
Note: See TracBrowser for help on using the repository browser.