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

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

fixed #3413: ProgressException when uploading osmChange file

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