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

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

fix #14788 - add robustness against invalid coordinates in .osm files

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