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

Last change on this file since 13650 was 13559, checked in by Don-vip, 6 years ago

extract DownloadPolicy / UploadPolicy to separate classes

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