001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.util.Collection;
009import java.util.Map.Entry;
010
011import jakarta.json.Json;
012import jakarta.json.JsonArray;
013import jakarta.json.JsonException;
014import jakarta.json.JsonNumber;
015import jakarta.json.JsonObject;
016import jakarta.json.JsonString;
017import jakarta.json.JsonValue;
018import jakarta.json.stream.JsonParser;
019import jakarta.json.stream.JsonParser.Event;
020import jakarta.json.stream.JsonParsingException;
021
022import org.openstreetmap.josm.data.osm.DataSet;
023import org.openstreetmap.josm.data.osm.PrimitiveData;
024import org.openstreetmap.josm.data.osm.RelationData;
025import org.openstreetmap.josm.data.osm.RelationMemberData;
026import org.openstreetmap.josm.data.osm.Tagged;
027import org.openstreetmap.josm.data.osm.WayData;
028import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
029import org.openstreetmap.josm.gui.progress.ProgressMonitor;
030import org.openstreetmap.josm.tools.Logging;
031import org.openstreetmap.josm.tools.UncheckedParseException;
032
033/**
034 * Parser for the Osm API (JSON output). Read from an input stream and construct a dataset out of it.
035 * <p>
036 * For each json element, there is a dedicated method.
037 * @since 14086
038 */
039public class OsmJsonReader extends AbstractReader {
040
041    protected JsonParser parser;
042
043    /**
044     * constructor (for private and subclasses use only)
045     *
046     * @see #parseDataSet(InputStream, ProgressMonitor)
047     */
048    protected OsmJsonReader() {
049        // Restricts visibility
050    }
051
052    protected void setParser(JsonParser parser) {
053        this.parser = parser;
054    }
055
056    protected void parse() throws IllegalDataException {
057        while (parser.hasNext()) {
058            Event event = parser.next();
059            if (event == Event.START_OBJECT) {
060                parseRoot(parser.getObject());
061            }
062        }
063        parser.close();
064    }
065
066    private void parseRoot(JsonObject object) throws IllegalDataException {
067        JsonValue version = object.get("version");
068        parseVersion(version != null ? version.toString() : null);
069        parseDownloadPolicy("download", object.getString("download", null));
070        parseUploadPolicy("upload", object.getString("upload", null));
071        parseLocked(object.getString("locked", null));
072        parseElements(object.getJsonArray("elements"));
073        parseRemark(object.getString("remark", null));
074    }
075
076    private void parseRemark(String remark) {
077        ds.setRemark(remark);
078    }
079
080    private void parseElements(JsonArray jsonArray) throws IllegalDataException {
081        for (JsonValue value : jsonArray) {
082            if (value instanceof JsonObject) {
083                JsonObject item = (JsonObject) value;
084                switch (item.getString("type")) {
085                case "node":
086                    parseNode(item);
087                    break;
088                case "way":
089                    parseWay(item);
090                    break;
091                case "relation":
092                    parseRelation(item);
093                    break;
094                default:
095                    parseUnknown(item);
096                }
097            } else {
098                throw new IllegalDataException("Unexpected JSON item: " + value);
099            }
100        }
101    }
102
103    /**
104     * Read out the common attributes and put them into current OsmPrimitive.
105     * @param item current JSON object
106     * @param current primitive to update
107     * @throws IllegalDataException if there is an error processing the underlying JSON source
108     */
109    private void readCommon(JsonObject item, PrimitiveData current) throws IllegalDataException {
110        try {
111            parseId(current, item.getJsonNumber("id").longValue());
112            parseTimestamp(current, item.getString("timestamp", null));
113            JsonNumber uid = item.getJsonNumber("uid");
114            if (uid != null) {
115                parseUser(current, item.getString("user", null), uid.longValue());
116            }
117            parseVisible(current, item.getString("visible", null));
118            JsonNumber version = item.getJsonNumber("version");
119            if (version != null) {
120                parseVersion(current, version.intValue());
121            }
122            parseAction(current, item.getString("action", null));
123            JsonNumber changeset = item.getJsonNumber("changeset");
124            if (changeset != null) {
125                parseChangeset(current, changeset.intValue());
126            }
127        } catch (UncheckedParseException e) {
128            throw new IllegalDataException(e);
129        }
130    }
131
132    private static void readTags(JsonObject item, Tagged t) {
133        JsonObject tags = item.getJsonObject("tags");
134        if (tags != null) {
135            for (Entry<String, JsonValue> entry : tags.entrySet()) {
136                t.put(entry.getKey(), ((JsonString) entry.getValue()).getString());
137            }
138        }
139    }
140
141    private void parseNode(JsonObject item) throws IllegalDataException {
142        parseNode(item.getJsonNumber("lat").doubleValue(),
143                  item.getJsonNumber("lon").doubleValue(), nd -> readCommon(item, nd), n -> readTags(item, n));
144    }
145
146    private void parseWay(JsonObject item) throws IllegalDataException {
147        parseWay(wd -> readCommon(item, wd), (w, nodeIds) -> readWayNodesAndTags(item, w, nodeIds));
148    }
149
150    private static void readWayNodesAndTags(JsonObject item, WayData w, Collection<Long> nodeIds) {
151        for (JsonValue v : item.getJsonArray("nodes")) {
152            nodeIds.add(((JsonNumber) v).longValue());
153        }
154        readTags(item, w);
155    }
156
157    private void parseRelation(JsonObject item) throws IllegalDataException {
158        parseRelation(rd -> readCommon(item, rd), (r, members) -> readRelationMembersAndTags(item, r, members));
159    }
160
161    private void readRelationMembersAndTags(JsonObject item, RelationData r, Collection<RelationMemberData> members)
162            throws IllegalDataException {
163        JsonArray jsonArray = item.getJsonArray("members");
164        if (jsonArray != null) {
165            for (JsonValue v : jsonArray) {
166                JsonObject o = v.asJsonObject();
167                members.add(parseRelationMember(r, ((JsonNumber) o.get("ref")).longValue(), o.getString("type"), o.getString("role")));
168            }
169        }
170        readTags(item, r);
171    }
172
173    protected void parseUnknown(JsonObject element, boolean printWarning) {
174        if (printWarning) {
175            Logging.info(tr("Undefined element ''{0}'' found in input stream. Skipping.", element));
176        }
177    }
178
179    private void parseUnknown(JsonObject element) {
180        parseUnknown(element, true);
181    }
182
183    @Override
184    protected DataSet doParseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
185        try {
186            return doParseDataSet(source, progressMonitor, (ParserWorker) ir -> {
187                setParser(Json.createParser(ir));
188                parse();
189            });
190        } catch (JsonParsingException exception) {
191            throw new IllegalDataException(exception);
192        } catch (JsonException exception) {
193            if (exception.getCause() instanceof IOException) {
194                IOException soe = (IOException) exception.getCause();
195                soe.addSuppressed(exception); // Add the caught exception as a suppressed exception
196                throw new IllegalDataException(soe);
197            }
198            throw exception;
199        }
200    }
201
202    /**
203     * Parse the given input source and return the dataset.
204     *
205     * @param source the source input stream. Must not be null.
206     * @param progressMonitor the progress monitor. If null, {@link NullProgressMonitor#INSTANCE} is assumed
207     *
208     * @return the dataset with the parsed data
209     * @throws IllegalDataException if an error was found while parsing the data from the source
210     * @throws IllegalArgumentException if source is null
211     */
212    public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
213        return new OsmJsonReader().doParseDataSet(source, progressMonitor);
214    }
215}