source: josm/trunk/src/org/openstreetmap/josm/io/GeoJSONReader.java@ 17107

Last change on this file since 17107 was 17107, checked in by GerdP, 4 years ago

fix #19822: Inconsistent behavior with GeoJSON multipolygons

  • replace untagged multipolygon member by tagged duplicate
  • Property svn:eol-style set to native
File size: 18.5 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.BufferedInputStream;
7import java.io.BufferedReader;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.InputStreamReader;
11import java.io.StringReader;
12import java.nio.charset.StandardCharsets;
13import java.util.ArrayList;
14import java.util.List;
15import java.util.Map;
16import java.util.Objects;
17import java.util.Optional;
18import java.util.TreeMap;
19import java.util.stream.Collectors;
20
21import javax.json.Json;
22import javax.json.JsonArray;
23import javax.json.JsonNumber;
24import javax.json.JsonObject;
25import javax.json.JsonString;
26import javax.json.JsonValue;
27import javax.json.stream.JsonParser;
28import javax.json.stream.JsonParser.Event;
29import javax.json.stream.JsonParsingException;
30
31import org.openstreetmap.josm.data.coor.EastNorth;
32import org.openstreetmap.josm.data.coor.LatLon;
33import org.openstreetmap.josm.data.osm.BBox;
34import org.openstreetmap.josm.data.osm.DataSet;
35import org.openstreetmap.josm.data.osm.Node;
36import org.openstreetmap.josm.data.osm.OsmPrimitive;
37import org.openstreetmap.josm.data.osm.Relation;
38import org.openstreetmap.josm.data.osm.RelationMember;
39import org.openstreetmap.josm.data.osm.UploadPolicy;
40import org.openstreetmap.josm.data.osm.Way;
41import org.openstreetmap.josm.data.projection.Projection;
42import org.openstreetmap.josm.data.projection.Projections;
43import org.openstreetmap.josm.data.validation.TestError;
44import org.openstreetmap.josm.data.validation.tests.DuplicateWay;
45import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
46import org.openstreetmap.josm.gui.progress.ProgressMonitor;
47import org.openstreetmap.josm.tools.Logging;
48import org.openstreetmap.josm.tools.Utils;
49
50/**
51 * Reader that reads GeoJSON files. See <a href="https://tools.ietf.org/html/rfc7946">RFC7946</a> for more information.
52 * @since 15424
53 */
54public class GeoJSONReader extends AbstractReader {
55
56 private static final String CRS = "crs";
57 private static final String NAME = "name";
58 private static final String LINK = "link";
59 private static final String COORDINATES = "coordinates";
60 private static final String FEATURES = "features";
61 private static final String PROPERTIES = "properties";
62 private static final String GEOMETRY = "geometry";
63 private static final String TYPE = "type";
64 /** The record separator is 0x1E per RFC 7464 */
65 private static final byte RECORD_SEPARATOR_BYTE = 0x1E;
66 private Projection projection = Projections.getProjectionByCode("EPSG:4326"); // WGS 84
67
68 GeoJSONReader() {
69 // Restricts visibility
70 }
71
72 private void parse(final JsonParser parser) throws IllegalDataException {
73 while (parser.hasNext()) {
74 Event event = parser.next();
75 if (event == Event.START_OBJECT) {
76 parseRoot(parser.getObject());
77 }
78 }
79 parser.close();
80 }
81
82 private void parseRoot(final JsonObject object) throws IllegalDataException {
83 parseCrs(object.getJsonObject(CRS));
84 switch (Optional.ofNullable(object.getJsonString(TYPE))
85 .orElseThrow(() -> new IllegalDataException("No type")).getString()) {
86 case "FeatureCollection":
87 parseFeatureCollection(object.getJsonArray(FEATURES));
88 break;
89 case "Feature":
90 parseFeature(object);
91 break;
92 case "GeometryCollection":
93 parseGeometryCollection(null, object);
94 break;
95 default:
96 parseGeometry(null, object);
97 }
98 }
99
100 /**
101 * Parse CRS as per https://geojson.org/geojson-spec.html#coordinate-reference-system-objects.
102 * CRS are obsolete in RFC7946 but still allowed for interoperability with older applications.
103 * Only named CRS are supported.
104 *
105 * @param crs CRS JSON object
106 * @throws IllegalDataException in case of error
107 */
108 private void parseCrs(final JsonObject crs) throws IllegalDataException {
109 if (crs != null) {
110 // Inspired by https://github.com/JOSM/geojson/commit/f13ceed4645244612a63581c96e20da802779c56
111 JsonObject properties = crs.getJsonObject("properties");
112 if (properties != null) {
113 switch (crs.getString(TYPE)) {
114 case NAME:
115 String crsName = properties.getString(NAME);
116 if ("urn:ogc:def:crs:OGC:1.3:CRS84".equals(crsName)) {
117 // https://osgeo-org.atlassian.net/browse/GEOT-1710
118 crsName = "EPSG:4326";
119 } else if (crsName.startsWith("urn:ogc:def:crs:EPSG:")) {
120 crsName = crsName.replace("urn:ogc:def:crs:", "");
121 }
122 projection = Optional.ofNullable(Projections.getProjectionByCode(crsName))
123 .orElse(Projections.getProjectionByCode("EPSG:4326")); // WGS84
124 break;
125 case LINK: // Not supported (security risk)
126 default:
127 throw new IllegalDataException(crs.toString());
128 }
129 }
130 }
131 }
132
133 private void parseFeatureCollection(final JsonArray features) {
134 for (JsonValue feature : features) {
135 if (feature instanceof JsonObject) {
136 parseFeature((JsonObject) feature);
137 }
138 }
139 }
140
141 private void parseFeature(final JsonObject feature) {
142 JsonValue geometry = feature.get(GEOMETRY);
143 if (geometry != null && geometry.getValueType() == JsonValue.ValueType.OBJECT) {
144 parseGeometry(feature, geometry.asJsonObject());
145 } else {
146 JsonValue properties = feature.get(PROPERTIES);
147 if (properties != null && properties.getValueType() == JsonValue.ValueType.OBJECT) {
148 parseNonGeometryFeature(feature, properties.asJsonObject());
149 } else {
150 Logging.warn(tr("Relation/non-geometry feature without properties found: {0}", feature));
151 }
152 }
153 }
154
155 private void parseNonGeometryFeature(final JsonObject feature, final JsonObject properties) {
156 // get relation type
157 JsonValue type = properties.get(TYPE);
158 if (type == null || properties.getValueType() == JsonValue.ValueType.STRING) {
159 Logging.warn(tr("Relation/non-geometry feature without type found: {0}", feature));
160 return;
161 }
162
163 // create misc. non-geometry feature
164 final Relation relation = new Relation();
165 relation.put(TYPE, type.toString());
166 fillTagsFromFeature(feature, relation);
167 getDataSet().addPrimitive(relation);
168 }
169
170 private void parseGeometryCollection(final JsonObject feature, final JsonObject geometry) {
171 for (JsonValue jsonValue : geometry.getJsonArray("geometries")) {
172 parseGeometry(feature, jsonValue.asJsonObject());
173 }
174 }
175
176 private void parseGeometry(final JsonObject feature, final JsonObject geometry) {
177 if (geometry == null) {
178 parseNullGeometry(feature);
179 return;
180 }
181
182 switch (geometry.getString(TYPE)) {
183 case "Point":
184 parsePoint(feature, geometry.getJsonArray(COORDINATES));
185 break;
186 case "MultiPoint":
187 parseMultiPoint(feature, geometry);
188 break;
189 case "LineString":
190 parseLineString(feature, geometry.getJsonArray(COORDINATES));
191 break;
192 case "MultiLineString":
193 parseMultiLineString(feature, geometry);
194 break;
195 case "Polygon":
196 parsePolygon(feature, geometry.getJsonArray(COORDINATES));
197 break;
198 case "MultiPolygon":
199 parseMultiPolygon(feature, geometry);
200 break;
201 case "GeometryCollection":
202 parseGeometryCollection(feature, geometry);
203 break;
204 default:
205 parseUnknown(geometry);
206 }
207 }
208
209 private LatLon getLatLon(final JsonArray coordinates) {
210 return projection.eastNorth2latlon(new EastNorth(
211 parseCoordinate(coordinates.get(0)),
212 parseCoordinate(coordinates.get(1))));
213 }
214
215 private static double parseCoordinate(JsonValue coordinate) {
216 if (coordinate instanceof JsonString) {
217 return Double.parseDouble(((JsonString) coordinate).getString());
218 } else if (coordinate instanceof JsonNumber) {
219 return ((JsonNumber) coordinate).doubleValue();
220 } else {
221 throw new IllegalArgumentException(Objects.toString(coordinate));
222 }
223 }
224
225 private void parsePoint(final JsonObject feature, final JsonArray coordinates) {
226 fillTagsFromFeature(feature, createNode(getLatLon(coordinates)));
227 }
228
229 private void parseMultiPoint(final JsonObject feature, final JsonObject geometry) {
230 for (JsonValue coordinate : geometry.getJsonArray(COORDINATES)) {
231 parsePoint(feature, coordinate.asJsonArray());
232 }
233 }
234
235 private void parseLineString(final JsonObject feature, final JsonArray coordinates) {
236 if (!coordinates.isEmpty()) {
237 createWay(coordinates, false)
238 .ifPresent(way -> fillTagsFromFeature(feature, way));
239 }
240 }
241
242 private void parseMultiLineString(final JsonObject feature, final JsonObject geometry) {
243 for (JsonValue coordinate : geometry.getJsonArray(COORDINATES)) {
244 parseLineString(feature, coordinate.asJsonArray());
245 }
246 }
247
248 private void parsePolygon(final JsonObject feature, final JsonArray coordinates) {
249 final int size = coordinates.size();
250 if (size == 1) {
251 createWay(coordinates.getJsonArray(0), true)
252 .ifPresent(way -> fillTagsFromFeature(feature, way));
253 } else if (size > 1) {
254 // create multipolygon
255 final Relation multipolygon = new Relation();
256 multipolygon.put(TYPE, "multipolygon");
257 createWay(coordinates.getJsonArray(0), true)
258 .ifPresent(way -> multipolygon.addMember(new RelationMember("outer", way)));
259
260 for (JsonValue interiorRing : coordinates.subList(1, size)) {
261 createWay(interiorRing.asJsonArray(), true)
262 .ifPresent(way -> multipolygon.addMember(new RelationMember("inner", way)));
263 }
264
265 fillTagsFromFeature(feature, multipolygon);
266 getDataSet().addPrimitive(multipolygon);
267 }
268 }
269
270 private void parseMultiPolygon(final JsonObject feature, final JsonObject geometry) {
271 for (JsonValue coordinate : geometry.getJsonArray(COORDINATES)) {
272 parsePolygon(feature, coordinate.asJsonArray());
273 }
274 }
275
276 private Node createNode(final LatLon latlon) {
277 final List<Node> existingNodes = getDataSet().searchNodes(new BBox(latlon, latlon));
278 if (!existingNodes.isEmpty()) {
279 // reuse existing node, avoid multiple nodes on top of each other
280 return existingNodes.get(0);
281 }
282 final Node node = new Node(latlon);
283 getDataSet().addPrimitive(node);
284 return node;
285 }
286
287 private Optional<Way> createWay(final JsonArray coordinates, final boolean autoClose) {
288 if (coordinates.isEmpty()) {
289 return Optional.empty();
290 }
291
292 final List<LatLon> latlons = coordinates.stream()
293 .map(coordinate -> getLatLon(coordinate.asJsonArray()))
294 .collect(Collectors.toList());
295
296 final int size = latlons.size();
297 final boolean doAutoclose;
298 if (size > 1) {
299 if (latlons.get(0).equals(latlons.get(size - 1))) {
300 doAutoclose = false; // already closed
301 } else {
302 doAutoclose = autoClose;
303 }
304 } else {
305 doAutoclose = false;
306 }
307
308 final Way way = new Way();
309 getDataSet().addPrimitive(way);
310 final List<Node> rawNodes = latlons.stream().map(this::createNode).collect(Collectors.toList());
311 if (doAutoclose) {
312 rawNodes.add(rawNodes.get(0));
313 }
314 // see #19833: remove duplicated references to the same node
315 final List<Node> wayNodes = new ArrayList<>(rawNodes.size());
316 Node last = null;
317 for (Node curr : rawNodes) {
318 if (last != curr)
319 wayNodes.add(curr);
320 last = curr;
321 }
322 way.setNodes(wayNodes);
323
324 return Optional.of(way);
325 }
326
327 private static void fillTagsFromFeature(final JsonObject feature, final OsmPrimitive primitive) {
328 if (feature != null) {
329 primitive.setKeys(getTags(feature));
330 }
331 }
332
333 private static void parseUnknown(final JsonObject object) {
334 Logging.warn(tr("Unknown json object found {0}", object));
335 }
336
337 private static void parseNullGeometry(JsonObject feature) {
338 Logging.warn(tr("Geometry of feature {0} is null", feature));
339 }
340
341 private static Map<String, String> getTags(final JsonObject feature) {
342 final Map<String, String> tags = new TreeMap<>();
343
344 if (feature.containsKey(PROPERTIES) && !feature.isNull(PROPERTIES)) {
345 JsonValue properties = feature.get(PROPERTIES);
346 if (properties != null && properties.getValueType() == JsonValue.ValueType.OBJECT) {
347 for (Map.Entry<String, JsonValue> stringJsonValueEntry : properties.asJsonObject().entrySet()) {
348 final JsonValue value = stringJsonValueEntry.getValue();
349
350 if (value instanceof JsonString) {
351 tags.put(stringJsonValueEntry.getKey(), ((JsonString) value).getString());
352 } else if (value instanceof JsonObject) {
353 Logging.warn(
354 "The GeoJSON contains an object with property '" + stringJsonValueEntry.getKey()
355 + "' whose value has the unsupported type '" + value.getClass().getSimpleName()
356 + "'. That key-value pair is ignored!"
357 );
358 } else if (value.getValueType() != JsonValue.ValueType.NULL) {
359 tags.put(stringJsonValueEntry.getKey(), value.toString());
360 }
361 }
362 }
363 }
364 return tags;
365 }
366
367 /**
368 * Check if the inputstream follows RFC 7464
369 * @param source The source to check (should be at the beginning)
370 * @return {@code true} if the initial character is {@link GeoJSONReader#RECORD_SEPARATOR_BYTE}.
371 */
372 private static boolean isLineDelimited(InputStream source) {
373 source.mark(2);
374 try {
375 int start = source.read();
376 if (RECORD_SEPARATOR_BYTE == start) {
377 return true;
378 }
379 source.reset();
380 } catch (IOException e) {
381 Logging.error(e);
382 }
383 return false;
384 }
385
386 @Override
387 protected DataSet doParseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
388 try (InputStream markSupported = source.markSupported() ? source : new BufferedInputStream(source)) {
389 ds.setUploadPolicy(UploadPolicy.DISCOURAGED);
390 if (isLineDelimited(markSupported)) {
391 try (BufferedReader reader = new BufferedReader(new InputStreamReader(markSupported, StandardCharsets.UTF_8))) {
392 String line;
393 String rs = new String(new byte[]{RECORD_SEPARATOR_BYTE}, StandardCharsets.US_ASCII);
394 while ((line = reader.readLine()) != null) {
395 line = Utils.strip(line, rs);
396 try (JsonParser parser = Json.createParser(new StringReader(line))) {
397 parse(parser);
398 }
399 }
400 }
401 } else {
402 try (JsonParser parser = Json.createParser(markSupported)) {
403 parse(parser);
404 }
405 }
406 mergeEqualMultipolygonWays();
407 } catch (IOException | JsonParsingException e) {
408 throw new IllegalDataException(e);
409 }
410 return getDataSet();
411 }
412
413 /**
414 * Import may create duplicate ways were one is member of a multipolygon and untagged and the other is tagged.
415 * Try to merge them here.
416 */
417 private void mergeEqualMultipolygonWays() {
418 DuplicateWay test = new DuplicateWay();
419 test.startTest(null);
420 for (Way w: getDataSet().getWays()) {
421 test.visit(w);
422 }
423 test.endTest();
424
425 if (test.getErrors().isEmpty())
426 return;
427
428 for (TestError e : test.getErrors()) {
429 if (e.getPrimitives().size() == 2 && !e.isFixable()) {
430 Way mpWay = null;
431 Way tagged = null;
432 for (OsmPrimitive p : e.getPrimitives()) {
433 if (p.isTagged() && p.referrers(Relation.class).count() == 0)
434 tagged = (Way) p;
435 else if (p.referrers(Relation.class).anyMatch(Relation::isMultipolygon))
436 mpWay = (Way) p;
437 }
438 if (mpWay != null && tagged != null) {
439 for (Relation r : mpWay.referrers(Relation.class).filter(Relation::isMultipolygon)
440 .collect(Collectors.toList())) {
441 for (int i = 0; i < r.getMembersCount(); i++) {
442 if (r.getMember(i).getMember().equals(mpWay)) {
443 r.setMember(i, new RelationMember(r.getRole(i), tagged));
444 }
445 }
446 }
447 mpWay.setDeleted(true);
448 }
449 }
450 }
451 ds.cleanupDeletedPrimitives();
452 }
453
454 /**
455 * Parse the given input source and return the dataset.
456 *
457 * @param source the source input stream. Must not be null.
458 * @param progressMonitor the progress monitor. If null, {@link NullProgressMonitor#INSTANCE} is assumed
459 * @return the dataset with the parsed data
460 * @throws IllegalDataException if an error was found while parsing the data from the source
461 * @throws IllegalArgumentException if source is null
462 */
463 public static DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
464 return new GeoJSONReader().doParseDataSet(source, progressMonitor);
465 }
466}
Note: See TracBrowser for help on using the repository browser.