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

Last change on this file since 4530 was 4530, checked in by Don-vip, 13 years ago

see #6653 and #6960 - Allow JOSM to download osmChange files again

  • Property svn:eol-style set to native
File size: 23.7 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.io.InputStreamReader;
8import java.text.MessageFormat;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.regex.Matcher;
12import java.util.regex.Pattern;
13
14import javax.xml.stream.Location;
15import javax.xml.stream.XMLInputFactory;
16import javax.xml.stream.XMLStreamConstants;
17import javax.xml.stream.XMLStreamException;
18import javax.xml.stream.XMLStreamReader;
19
20import org.openstreetmap.josm.data.Bounds;
21import org.openstreetmap.josm.data.coor.LatLon;
22import org.openstreetmap.josm.data.osm.Changeset;
23import org.openstreetmap.josm.data.osm.DataSet;
24import org.openstreetmap.josm.data.osm.DataSource;
25import org.openstreetmap.josm.data.osm.Node;
26import org.openstreetmap.josm.data.osm.NodeData;
27import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
28import org.openstreetmap.josm.data.osm.PrimitiveData;
29import org.openstreetmap.josm.data.osm.Relation;
30import org.openstreetmap.josm.data.osm.RelationData;
31import org.openstreetmap.josm.data.osm.RelationMemberData;
32import org.openstreetmap.josm.data.osm.Tagged;
33import org.openstreetmap.josm.data.osm.User;
34import org.openstreetmap.josm.data.osm.Way;
35import org.openstreetmap.josm.data.osm.WayData;
36import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
37import org.openstreetmap.josm.gui.progress.ProgressMonitor;
38import org.openstreetmap.josm.tools.CheckParameterUtil;
39import org.openstreetmap.josm.tools.DateUtils;
40
41/**
42 * Parser for the Osm Api. Read from an input stream and construct a dataset out of it.
43 *
44 * For each xml element, there is a dedicated method.
45 * The XMLStreamReader cursor points to the start of the element, when the method is
46 * entered, and it must point to the end of the same element, when it is exited.
47 */
48public class OsmReader extends AbstractReader {
49
50 protected XMLStreamReader parser;
51
52 /**
53 * constructor (for private and subclasses use only)
54 *
55 * @see #parseDataSet(InputStream, DataSet, ProgressMonitor)
56 */
57 protected OsmReader() {
58 }
59
60 protected void setParser(XMLStreamReader parser) {
61 this.parser = parser;
62 }
63
64 protected void throwException(String msg) throws XMLStreamException {
65 throw new OsmParsingException(msg, parser.getLocation());
66 }
67
68 protected void parse() throws XMLStreamException {
69 int event = parser.getEventType();
70 while (true) {
71 if (event == XMLStreamConstants.START_ELEMENT) {
72 parseRoot();
73 } else if (event == XMLStreamConstants.END_ELEMENT) {
74 return;
75 }
76 if (parser.hasNext()) {
77 event = parser.next();
78 } else {
79 break;
80 }
81 }
82 parser.close();
83 }
84
85 protected void parseRoot() throws XMLStreamException {
86 if (parser.getLocalName().equals("osm")) {
87 parseOsm();
88 } else {
89 parseUnknown();
90 }
91 }
92
93 private void parseOsm() throws XMLStreamException {
94 String v = parser.getAttributeValue(null, "version");
95 if (v == null) {
96 throwException(tr("Missing mandatory attribute ''{0}''.", "version"));
97 }
98 if (!(v.equals("0.5") || v.equals("0.6"))) {
99 throwException(tr("Unsupported version: {0}", v));
100 }
101 ds.setVersion(v);
102 String generator = parser.getAttributeValue(null, "generator");
103 Long uploadChangesetId = null;
104 if (parser.getAttributeValue(null, "upload-changeset") != null) {
105 uploadChangesetId = getLong("upload-changeset");
106 }
107 while (true) {
108 int event = parser.next();
109 if (event == XMLStreamConstants.START_ELEMENT) {
110 if (parser.getLocalName().equals("bounds")) {
111 parseBounds(generator);
112 } else if (parser.getLocalName().equals("node")) {
113 parseNode();
114 } else if (parser.getLocalName().equals("way")) {
115 parseWay();
116 } else if (parser.getLocalName().equals("relation")) {
117 parseRelation();
118 } else if (parser.getLocalName().equals("changeset")) {
119 parseChangeset(uploadChangesetId);
120 } else {
121 parseUnknown();
122 }
123 } else if (event == XMLStreamConstants.END_ELEMENT) {
124 return;
125 }
126 }
127 }
128
129 private void parseBounds(String generator) throws XMLStreamException {
130 String minlon = parser.getAttributeValue(null, "minlon");
131 String minlat = parser.getAttributeValue(null, "minlat");
132 String maxlon = parser.getAttributeValue(null, "maxlon");
133 String maxlat = parser.getAttributeValue(null, "maxlat");
134 String origin = parser.getAttributeValue(null, "origin");
135 if (minlon != null && maxlon != null && minlat != null && maxlat != null) {
136 if (origin == null) {
137 origin = generator;
138 }
139 Bounds bounds = new Bounds(
140 Double.parseDouble(minlat), Double.parseDouble(minlon),
141 Double.parseDouble(maxlat), Double.parseDouble(maxlon));
142 if (bounds.isOutOfTheWorld()) {
143 Bounds copy = new Bounds(bounds);
144 bounds.normalize();
145 System.out.println("Bbox " + copy + " is out of the world, normalized to " + bounds);
146 }
147 DataSource src = new DataSource(bounds, origin);
148 ds.dataSources.add(src);
149 } else {
150 throwException(tr(
151 "Missing mandatory attributes on element ''bounds''. Got minlon=''{0}'',minlat=''{1}'',maxlon=''{3}'',maxlat=''{4}'', origin=''{5}''.",
152 minlon, minlat, maxlon, maxlat, origin
153 ));
154 }
155 jumpToEnd();
156 }
157
158 protected void parseNode() throws XMLStreamException {
159 NodeData nd = new NodeData();
160 nd.setCoor(new LatLon(Double.parseDouble(parser.getAttributeValue(null, "lat")), Double.parseDouble(parser.getAttributeValue(null, "lon"))));
161 readCommon(nd);
162 Node n = new Node(nd.getId(), nd.getVersion());
163 n.setVisible(nd.isVisible());
164 n.load(nd);
165 externalIdMap.put(nd.getPrimitiveId(), n);
166 while (true) {
167 int event = parser.next();
168 if (event == XMLStreamConstants.START_ELEMENT) {
169 if (parser.getLocalName().equals("tag")) {
170 parseTag(n);
171 } else {
172 parseUnknown();
173 }
174 } else if (event == XMLStreamConstants.END_ELEMENT) {
175 return;
176 }
177 }
178 }
179
180 protected void parseWay() throws XMLStreamException {
181 WayData wd = new WayData();
182 readCommon(wd);
183 Way w = new Way(wd.getId(), wd.getVersion());
184 w.setVisible(wd.isVisible());
185 w.load(wd);
186 externalIdMap.put(wd.getPrimitiveId(), w);
187
188 Collection<Long> nodeIds = new ArrayList<Long>();
189 while (true) {
190 int event = parser.next();
191 if (event == XMLStreamConstants.START_ELEMENT) {
192 if (parser.getLocalName().equals("nd")) {
193 nodeIds.add(parseWayNode(w));
194 } else if (parser.getLocalName().equals("tag")) {
195 parseTag(w);
196 } else {
197 parseUnknown();
198 }
199 } else if (event == XMLStreamConstants.END_ELEMENT) {
200 break;
201 }
202 }
203 if (w.isDeleted() && nodeIds.size() > 0) {
204 System.out.println(tr("Deleted way {0} contains nodes", w.getUniqueId()));
205 nodeIds = new ArrayList<Long>();
206 }
207 ways.put(wd.getUniqueId(), nodeIds);
208 }
209
210 private long parseWayNode(Way w) throws XMLStreamException {
211 if (parser.getAttributeValue(null, "ref") == null) {
212 throwException(
213 tr("Missing mandatory attribute ''{0}'' on <nd> of way {1}.", "ref", w.getUniqueId())
214 );
215 }
216 long id = getLong("ref");
217 if (id == 0) {
218 throwException(
219 tr("Illegal value of attribute ''ref'' of element <nd>. Got {0}.", id)
220 );
221 }
222 jumpToEnd();
223 return id;
224 }
225
226 protected void parseRelation() throws XMLStreamException {
227 RelationData rd = new RelationData();
228 readCommon(rd);
229 Relation r = new Relation(rd.getId(), rd.getVersion());
230 r.setVisible(rd.isVisible());
231 r.load(rd);
232 externalIdMap.put(rd.getPrimitiveId(), r);
233
234 Collection<RelationMemberData> members = new ArrayList<RelationMemberData>();
235 while (true) {
236 int event = parser.next();
237 if (event == XMLStreamConstants.START_ELEMENT) {
238 if (parser.getLocalName().equals("member")) {
239 members.add(parseRelationMember(r));
240 } else if (parser.getLocalName().equals("tag")) {
241 parseTag(r);
242 } else {
243 parseUnknown();
244 }
245 } else if (event == XMLStreamConstants.END_ELEMENT) {
246 break;
247 }
248 }
249 if (r.isDeleted() && members.size() > 0) {
250 System.out.println(tr("Deleted relation {0} contains members", r.getUniqueId()));
251 members = new ArrayList<RelationMemberData>();
252 }
253 relations.put(rd.getUniqueId(), members);
254 }
255
256 private RelationMemberData parseRelationMember(Relation r) throws XMLStreamException {
257 String role = null;
258 OsmPrimitiveType type = null;
259 long id = 0;
260 String value = parser.getAttributeValue(null, "ref");
261 if (value == null) {
262 throwException(tr("Missing attribute ''ref'' on member in relation {0}.",r.getUniqueId()));
263 }
264 try {
265 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(r.getUniqueId()),value));
268 }
269 value = parser.getAttributeValue(null, "type");
270 if (value == null) {
271 throwException(tr("Missing attribute ''type'' on member {0} in relation {1}.", Long.toString(id), Long.toString(r.getUniqueId())));
272 }
273 try {
274 type = OsmPrimitiveType.fromApiTypeName(value);
275 } catch(IllegalArgumentException e) {
276 throwException(tr("Illegal value for attribute ''type'' on member {0} in relation {1}. Got {2}.", Long.toString(id), Long.toString(r.getUniqueId()), value));
277 }
278 value = parser.getAttributeValue(null, "role");
279 role = value;
280
281 if (id == 0) {
282 throwException(tr("Incomplete <member> specification with ref=0"));
283 }
284 jumpToEnd();
285 return new RelationMemberData(role, type, id);
286 }
287
288 private void parseChangeset(Long uploadChangesetId) throws XMLStreamException {
289 long id = getLong("id");
290
291 if (id == uploadChangesetId) {
292 uploadChangeset = new Changeset((int) getLong("id"));
293 while (true) {
294 int event = parser.next();
295 if (event == XMLStreamConstants.START_ELEMENT) {
296 if (parser.getLocalName().equals("tag")) {
297 parseTag(uploadChangeset);
298 } else {
299 parseUnknown();
300 }
301 } else if (event == XMLStreamConstants.END_ELEMENT) {
302 return;
303 }
304 }
305 } else {
306 jumpToEnd(false);
307 }
308 }
309
310 private void parseTag(Tagged t) throws XMLStreamException {
311 String key = parser.getAttributeValue(null, "k");
312 String value = parser.getAttributeValue(null, "v");
313 if (key == null || value == null) {
314 throwException(tr("Missing key or value attribute in tag."));
315 }
316 t.put(key.intern(), value.intern());
317 jumpToEnd();
318 }
319
320 protected void parseUnknown(boolean printWarning) throws XMLStreamException {
321 if (printWarning) {
322 System.out.println(tr("Undefined element ''{0}'' found in input stream. Skipping.", parser.getLocalName()));
323 }
324 while (true) {
325 int event = parser.next();
326 if (event == XMLStreamConstants.START_ELEMENT) {
327 parseUnknown(false); /* no more warning for inner elements */
328 } else if (event == XMLStreamConstants.END_ELEMENT) {
329 return;
330 }
331 }
332 }
333
334 protected void parseUnknown() throws XMLStreamException {
335 parseUnknown(true);
336 }
337
338 /**
339 * When cursor is at the start of an element, moves it to the end tag of that element.
340 * Nested content is skipped.
341 *
342 * This is basically the same code as parseUnkown(), except for the warnings, which
343 * are displayed for inner elements and not at top level.
344 */
345 private void jumpToEnd(boolean printWarning) throws XMLStreamException {
346 while (true) {
347 int event = parser.next();
348 if (event == XMLStreamConstants.START_ELEMENT) {
349 parseUnknown(printWarning);
350 } else if (event == XMLStreamConstants.END_ELEMENT) {
351 return;
352 }
353 }
354 }
355
356 private void jumpToEnd() throws XMLStreamException {
357 jumpToEnd(true);
358 }
359
360 private User createUser(String uid, String name) throws XMLStreamException {
361 if (uid == null) {
362 if (name == null)
363 return null;
364 return User.createLocalUser(name);
365 }
366 try {
367 long id = Long.parseLong(uid);
368 return User.createOsmUser(id, name);
369 } catch(NumberFormatException e) {
370 throwException(MessageFormat.format("Illegal value for attribute ''uid''. Got ''{0}''.", uid));
371 }
372 return null;
373 }
374
375 /**
376 * Read out the common attributes and put them into current OsmPrimitive.
377 */
378 private void readCommon(PrimitiveData current) throws XMLStreamException {
379 current.setId(getLong("id"));
380 if (current.getUniqueId() == 0) {
381 throwException(tr("Illegal object with ID=0."));
382 }
383
384 String time = parser.getAttributeValue(null, "timestamp");
385 if (time != null && time.length() != 0) {
386 current.setTimestamp(DateUtils.fromString(time));
387 }
388
389 // user attribute added in 0.4 API
390 String user = parser.getAttributeValue(null, "user");
391 // uid attribute added in 0.6 API
392 String uid = parser.getAttributeValue(null, "uid");
393 current.setUser(createUser(uid, user));
394
395 // visible attribute added in 0.4 API
396 String visible = parser.getAttributeValue(null, "visible");
397 if (visible != null) {
398 current.setVisible(Boolean.parseBoolean(visible));
399 }
400
401 String versionString = parser.getAttributeValue(null, "version");
402 int version = 0;
403 if (versionString != null) {
404 try {
405 version = Integer.parseInt(versionString);
406 } catch(NumberFormatException e) {
407 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.", Long.toString(current.getUniqueId()), versionString));
408 }
409 if (ds.getVersion().equals("0.6")){
410 if (version <= 0 && current.getUniqueId() > 0) {
411 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.", Long.toString(current.getUniqueId()), versionString));
412 } else if (version < 0 && current.getUniqueId() <= 0) {
413 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"));
414 version = 0;
415 }
416 } else if (ds.getVersion().equals("0.5")) {
417 if (version <= 0 && current.getUniqueId() > 0) {
418 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"));
419 version = 1;
420 } else if (version < 0 && current.getUniqueId() <= 0) {
421 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"));
422 version = 0;
423 }
424 } else {
425 // should not happen. API version has been checked before
426 throwException(tr("Unknown or unsupported API version. Got {0}.", ds.getVersion()));
427 }
428 } else {
429 // version expected for OSM primitives with an id assigned by the server (id > 0), since API 0.6
430 //
431 if (current.getUniqueId() > 0 && ds.getVersion() != null && ds.getVersion().equals("0.6")) {
432 throwException(tr("Missing attribute ''version'' on OSM primitive with ID {0}.", Long.toString(current.getUniqueId())));
433 } else if (current.getUniqueId() > 0 && ds.getVersion() != null && ds.getVersion().equals("0.5")) {
434 // default version in 0.5 files for existing primitives
435 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"));
436 version= 1;
437 } else if (current.getUniqueId() <= 0 && ds.getVersion() != null && ds.getVersion().equals("0.5")) {
438 // default version in 0.5 files for new primitives, no warning necessary. This is
439 // (was) legal in API 0.5
440 version= 0;
441 }
442 }
443 current.setVersion(version);
444
445 String action = parser.getAttributeValue(null, "action");
446 if (action == null) {
447 // do nothing
448 } else if (action.equals("delete")) {
449 current.setDeleted(true);
450 current.setModified(current.isVisible());
451 } else if (action.equals("modify")) {
452 current.setModified(true);
453 }
454
455 String v = parser.getAttributeValue(null, "changeset");
456 if (v == null) {
457 current.setChangesetId(0);
458 } else {
459 try {
460 current.setChangesetId(Integer.parseInt(v));
461 } catch(NumberFormatException e) {
462 if (current.getUniqueId() <= 0) {
463 // for a new primitive we just log a warning
464 System.out.println(tr("Illegal value for attribute ''changeset'' on new object {1}. Got {0}. Resetting to 0.", v, current.getUniqueId()));
465 current.setChangesetId(0);
466 } else {
467 // for an existing primitive this is a problem
468 throwException(tr("Illegal value for attribute ''changeset''. Got {0}.", v));
469 }
470 }
471 if (current.getChangesetId() <=0) {
472 if (current.getUniqueId() <= 0) {
473 // for a new primitive we just log a warning
474 System.out.println(tr("Illegal value for attribute ''changeset'' on new object {1}. Got {0}. Resetting to 0.", v, current.getUniqueId()));
475 current.setChangesetId(0);
476 } else {
477 // for an existing primitive this is a problem
478 throwException(tr("Illegal value for attribute ''changeset''. Got {0}.", v));
479 }
480 }
481 }
482 }
483
484 private long getLong(String name) throws XMLStreamException {
485 String value = parser.getAttributeValue(null, name);
486 if (value == null) {
487 throwException(tr("Missing required attribute ''{0}''.",name));
488 }
489 try {
490 return Long.parseLong(value);
491 } catch(NumberFormatException e) {
492 throwException(tr("Illegal long value for attribute ''{0}''. Got ''{1}''.",name, value));
493 }
494 return 0; // should not happen
495 }
496
497 private static class OsmParsingException extends XMLStreamException {
498 public OsmParsingException() {
499 super();
500 }
501
502 public OsmParsingException(String msg) {
503 super(msg);
504 }
505
506 public OsmParsingException(String msg, Location location) {
507 super(msg); /* cannot use super(msg, location) because it messes with the message preventing localization */
508 this.location = location;
509 }
510
511 public OsmParsingException(String msg, Location location, Throwable th) {
512 super(msg, th);
513 this.location = location;
514 }
515
516 public OsmParsingException(String msg, Throwable th) {
517 super(msg, th);
518 }
519
520 public OsmParsingException(Throwable th) {
521 super(th);
522 }
523
524 @Override
525 public String getMessage() {
526 String msg = super.getMessage();
527 if (msg == null) {
528 msg = getClass().getName();
529 }
530 if (getLocation() == null)
531 return msg;
532 msg = msg + " " + tr("(at line {0}, column {1})", getLocation().getLineNumber(), getLocation().getColumnNumber());
533 return msg;
534 }
535 }
536
537 protected DataSet doParseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
538 if (progressMonitor == null) {
539 progressMonitor = NullProgressMonitor.INSTANCE;
540 }
541 CheckParameterUtil.ensureParameterNotNull(source, "source");
542 try {
543 progressMonitor.beginTask(tr("Prepare OSM data...", 2));
544 progressMonitor.indeterminateSubTask(tr("Parsing OSM data..."));
545
546 InputStreamReader ir = UTFInputStreamReader.create(source, "UTF-8");
547 XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
548 setParser(parser);
549 parse();
550 progressMonitor.worked(1);
551
552 progressMonitor.indeterminateSubTask(tr("Preparing data set..."));
553 prepareDataSet();
554 progressMonitor.worked(1);
555 return getDataSet();
556 } catch(IllegalDataException e) {
557 throw e;
558 } catch(OsmParsingException e) {
559 throw new IllegalDataException(e.getMessage(), e);
560 } catch(XMLStreamException e) {
561 String msg = e.getMessage();
562 Pattern p = Pattern.compile("Message: (.+)");
563 Matcher m = p.matcher(msg);
564 if (m.find()) {
565 msg = m.group(1);
566 }
567 if (e.getLocation() != null) {
568 throw new IllegalDataException(tr("Line {0} column {1}: ", e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()) + msg, e);
569 } else {
570 throw new IllegalDataException(msg, e);
571 }
572 } catch(Exception e) {
573 throw new IllegalDataException(e);
574 } finally {
575 progressMonitor.finishTask();
576 }
577 }
578
579 /**
580 * Parse the given input source and return the dataset.
581 *
582 * @param source the source input stream. Must not be null.
583 * @param progressMonitor the progress monitor. If null, {@see NullProgressMonitor#INSTANCE} is assumed
584 *
585 * @return the dataset with the parsed data
586 * @throws IllegalDataException thrown if the an error was found while parsing the data from the source
587 * @throws IllegalArgumentException thrown if source is null
588 */
589 public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
590 return new OsmReader().doParseDataSet(source, progressMonitor);
591 }
592}
Note: See TracBrowser for help on using the repository browser.