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

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

checkstyle: enable relevant whitespace checks and fix them

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