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

Revision 5025, 24.8 KB checked in by Don-vip, 3 months ago (diff)

see #4043 - Have an 'upload prohibited' flag in .osm files

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