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

Last change on this file since 8418 was 8415, checked in by Don-vip, 9 years ago

code style/cleanup - Uncommented Empty Constructor

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