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

Last change on this file since 9171 was 9087, checked in by Don-vip, 8 years ago

sonar - fix some errors, mainly NPEs

  • Property svn:eol-style set to native
File size: 25.4 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("Missing mandatory attributes on element ''bounds''. " +
192 "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()),
320 value), e);
321 }
322 value = parser.getAttributeValue(null, "type");
323 if (value == null) {
324 throwException(tr("Missing attribute ''type'' on member {0} in relation {1}.", Long.toString(id), Long.toString(r.getUniqueId())));
325 }
326 try {
327 type = OsmPrimitiveType.fromApiTypeName(value);
328 } catch (IllegalArgumentException e) {
329 throwException(tr("Illegal value for attribute ''type'' on member {0} in relation {1}. Got {2}.",
330 Long.toString(id), Long.toString(r.getUniqueId()), value), e);
331 }
332 value = parser.getAttributeValue(null, "role");
333 role = value;
334
335 if (id == 0) {
336 throwException(tr("Incomplete <member> specification with ref=0"));
337 }
338 jumpToEnd();
339 return new RelationMemberData(role, type, id);
340 }
341
342 private void parseChangeset(Long uploadChangesetId) throws XMLStreamException {
343
344 Long id = null;
345 if (parser.getAttributeValue(null, "id") != null) {
346 id = getLong("id");
347 }
348 // Read changeset info if neither upload-changeset nor id are set, or if they are both set to the same value
349 if (id == uploadChangesetId || (id != null && id.equals(uploadChangesetId))) {
350 uploadChangeset = new Changeset(id != null ? id.intValue() : 0);
351 while (true) {
352 int event = parser.next();
353 if (event == XMLStreamConstants.START_ELEMENT) {
354 if ("tag".equals(parser.getLocalName())) {
355 parseTag(uploadChangeset);
356 } else {
357 parseUnknown();
358 }
359 } else if (event == XMLStreamConstants.END_ELEMENT)
360 return;
361 }
362 } else {
363 jumpToEnd(false);
364 }
365 }
366
367 private void parseTag(Tagged t) throws XMLStreamException {
368 String key = parser.getAttributeValue(null, "k");
369 String value = parser.getAttributeValue(null, "v");
370 if (key == null || value == null) {
371 throwException(tr("Missing key or value attribute in tag."));
372 } else {
373 t.put(key.intern(), value.intern());
374 }
375 jumpToEnd();
376 }
377
378 protected void parseUnknown(boolean printWarning) throws XMLStreamException {
379 if (printWarning) {
380 Main.info(tr("Undefined element ''{0}'' found in input stream. Skipping.", parser.getLocalName()));
381 }
382 while (true) {
383 int event = parser.next();
384 if (event == XMLStreamConstants.START_ELEMENT) {
385 parseUnknown(false); /* no more warning for inner elements */
386 } else if (event == XMLStreamConstants.END_ELEMENT)
387 return;
388 }
389 }
390
391 protected void parseUnknown() throws XMLStreamException {
392 parseUnknown(true);
393 }
394
395 /**
396 * When cursor is at the start of an element, moves it to the end tag of that element.
397 * Nested content is skipped.
398 *
399 * This is basically the same code as parseUnknown(), except for the warnings, which
400 * are displayed for inner elements and not at top level.
401 * @throws XMLStreamException if there is an error processing the underlying XML source
402 */
403 private void jumpToEnd(boolean printWarning) throws XMLStreamException {
404 while (true) {
405 int event = parser.next();
406 if (event == XMLStreamConstants.START_ELEMENT) {
407 parseUnknown(printWarning);
408 } else if (event == XMLStreamConstants.END_ELEMENT)
409 return;
410 }
411 }
412
413 private void jumpToEnd() throws XMLStreamException {
414 jumpToEnd(true);
415 }
416
417 private User createUser(String uid, String name) throws XMLStreamException {
418 if (uid == null) {
419 if (name == null)
420 return null;
421 return User.createLocalUser(name);
422 }
423 try {
424 long id = Long.parseLong(uid);
425 return User.createOsmUser(id, name);
426 } catch (NumberFormatException e) {
427 throwException(MessageFormat.format("Illegal value for attribute ''uid''. Got ''{0}''.", uid), e);
428 }
429 return null;
430 }
431
432 /**
433 * Read out the common attributes and put them into current OsmPrimitive.
434 * @throws XMLStreamException if there is an error processing the underlying XML source
435 */
436 private void readCommon(PrimitiveData current) throws XMLStreamException {
437 current.setId(getLong("id"));
438 if (current.getUniqueId() == 0) {
439 throwException(tr("Illegal object with ID=0."));
440 }
441
442 String time = parser.getAttributeValue(null, "timestamp");
443 if (time != null && !time.isEmpty()) {
444 current.setRawTimestamp((int) (DateUtils.tsFromString(time)/1000));
445 }
446
447 String user = parser.getAttributeValue(null, "user");
448 String uid = parser.getAttributeValue(null, "uid");
449 current.setUser(createUser(uid, user));
450
451 String visible = parser.getAttributeValue(null, "visible");
452 if (visible != null) {
453 current.setVisible(Boolean.parseBoolean(visible));
454 }
455
456 String versionString = parser.getAttributeValue(null, "version");
457 int version = 0;
458 if (versionString != null) {
459 try {
460 version = Integer.parseInt(versionString);
461 } catch (NumberFormatException e) {
462 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.",
463 Long.toString(current.getUniqueId()), versionString), e);
464 }
465 switch (ds.getVersion()) {
466 case "0.6":
467 if (version <= 0 && !current.isNew()) {
468 throwException(tr("Illegal value for attribute ''version'' on OSM primitive with ID {0}. Got {1}.",
469 Long.toString(current.getUniqueId()), versionString));
470 } else if (version < 0 && current.isNew()) {
471 Main.warn(tr("Normalizing value of attribute ''version'' of element {0} to {2}, API version is ''{3}''. Got {1}.",
472 current.getUniqueId(), version, 0, "0.6"));
473 version = 0;
474 }
475 break;
476 default:
477 // should not happen. API version has been checked before
478 throwException(tr("Unknown or unsupported API version. Got {0}.", ds.getVersion()));
479 }
480 } else {
481 // version expected for OSM primitives with an id assigned by the server (id > 0), since API 0.6
482 if (!current.isNew() && ds.getVersion() != null && "0.6".equals(ds.getVersion())) {
483 throwException(tr("Missing attribute ''version'' on OSM primitive with ID {0}.", Long.toString(current.getUniqueId())));
484 }
485 }
486 current.setVersion(version);
487
488 String action = parser.getAttributeValue(null, "action");
489 if (action == null) {
490 // do nothing
491 } else if ("delete".equals(action)) {
492 current.setDeleted(true);
493 current.setModified(current.isVisible());
494 } else if ("modify".equals(action)) {
495 current.setModified(true);
496 }
497
498 String v = parser.getAttributeValue(null, "changeset");
499 if (v == null) {
500 current.setChangesetId(0);
501 } else {
502 try {
503 current.setChangesetId(Integer.parseInt(v));
504 } catch (IllegalArgumentException e) {
505 Main.debug(e.getMessage());
506 if (current.isNew()) {
507 // for a new primitive we just log a warning
508 Main.info(tr("Illegal value for attribute ''changeset'' on new object {1}. Got {0}. Resetting to 0.",
509 v, current.getUniqueId()));
510 current.setChangesetId(0);
511 } else {
512 // for an existing primitive this is a problem
513 throwException(tr("Illegal value for attribute ''changeset''. Got {0}.", v), e);
514 }
515 } catch (IllegalStateException e) {
516 // thrown for positive changeset id on new primitives
517 Main.info(e.getMessage());
518 current.setChangesetId(0);
519 }
520 if (current.getChangesetId() <= 0) {
521 if (current.isNew()) {
522 // for a new primitive we just log a warning
523 Main.info(tr("Illegal value for attribute ''changeset'' on new object {1}. Got {0}. Resetting to 0.",
524 v, current.getUniqueId()));
525 current.setChangesetId(0);
526 } else {
527 // for an existing primitive this is a problem
528 throwException(tr("Illegal value for attribute ''changeset''. Got {0}.", v));
529 }
530 }
531 }
532 }
533
534 private long getLong(String name) throws XMLStreamException {
535 String value = parser.getAttributeValue(null, name);
536 if (value == null) {
537 throwException(tr("Missing required attribute ''{0}''.", name));
538 }
539 try {
540 return Long.parseLong(value);
541 } catch (NumberFormatException e) {
542 throwException(tr("Illegal long value for attribute ''{0}''. Got ''{1}''.", name, value), e);
543 }
544 return 0; // should not happen
545 }
546
547 private static class OsmParsingException extends XMLStreamException {
548
549 OsmParsingException(String msg, Location location) {
550 super(msg); /* cannot use super(msg, location) because it messes with the message preventing localization */
551 this.location = location;
552 }
553
554 OsmParsingException(String msg, Location location, Throwable th) {
555 super(msg, th);
556 this.location = location;
557 }
558
559 @Override
560 public String getMessage() {
561 String msg = super.getMessage();
562 if (msg == null) {
563 msg = getClass().getName();
564 }
565 if (getLocation() == null)
566 return msg;
567 msg += ' ' + tr("(at line {0}, column {1})", getLocation().getLineNumber(), getLocation().getColumnNumber());
568 int offset = getLocation().getCharacterOffset();
569 if (offset > -1) {
570 msg += ". "+ tr("{0} bytes have been read", offset);
571 }
572 return msg;
573 }
574 }
575
576 /**
577 * Exception thrown after user cancelation.
578 */
579 private static final class OsmParsingCanceledException extends OsmParsingException implements ImportCancelException {
580 /**
581 * Constructs a new {@code OsmParsingCanceledException}.
582 * @param msg The error message
583 * @param location The parser location
584 */
585 OsmParsingCanceledException(String msg, Location location) {
586 super(msg, location);
587 }
588 }
589
590 protected DataSet doParseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
591 if (progressMonitor == null) {
592 progressMonitor = NullProgressMonitor.INSTANCE;
593 }
594 ProgressMonitor.CancelListener cancelListener = new ProgressMonitor.CancelListener() {
595 @Override public void operationCanceled() {
596 cancel = true;
597 }
598 };
599 progressMonitor.addCancelListener(cancelListener);
600 CheckParameterUtil.ensureParameterNotNull(source, "source");
601 try {
602 progressMonitor.beginTask(tr("Prepare OSM data...", 2));
603 progressMonitor.indeterminateSubTask(tr("Parsing OSM data..."));
604
605 try (InputStreamReader ir = UTFInputStreamReader.create(source)) {
606 XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
607 setParser(parser);
608 parse();
609 }
610 progressMonitor.worked(1);
611
612 progressMonitor.indeterminateSubTask(tr("Preparing data set..."));
613 prepareDataSet();
614 progressMonitor.worked(1);
615
616 // iterate over registered postprocessors and give them each a chance
617 // to modify the dataset we have just loaded.
618 if (postprocessors != null) {
619 for (OsmServerReadPostprocessor pp : postprocessors) {
620 pp.postprocessDataSet(getDataSet(), progressMonitor);
621 }
622 }
623 return getDataSet();
624 } catch (IllegalDataException e) {
625 throw e;
626 } catch (OsmParsingException e) {
627 throw new IllegalDataException(e.getMessage(), e);
628 } catch (XMLStreamException e) {
629 String msg = e.getMessage();
630 Pattern p = Pattern.compile("Message: (.+)");
631 Matcher m = p.matcher(msg);
632 if (m.find()) {
633 msg = m.group(1);
634 }
635 if (e.getLocation() != null)
636 throw new IllegalDataException(tr("Line {0} column {1}: ",
637 e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()) + msg, e);
638 else
639 throw new IllegalDataException(msg, e);
640 } catch (Exception e) {
641 throw new IllegalDataException(e);
642 } finally {
643 progressMonitor.finishTask();
644 progressMonitor.removeCancelListener(cancelListener);
645 }
646 }
647
648 /**
649 * Parse the given input source and return the dataset.
650 *
651 * @param source the source input stream. Must not be null.
652 * @param progressMonitor the progress monitor. If null, {@link NullProgressMonitor#INSTANCE} is assumed
653 *
654 * @return the dataset with the parsed data
655 * @throws IllegalDataException if an error was found while parsing the data from the source
656 * @throws IllegalArgumentException if source is null
657 */
658 public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
659 return new OsmReader().doParseDataSet(source, progressMonitor);
660 }
661}
Note: See TracBrowser for help on using the repository browser.