use of org.opensearch.geometry.Polygon in project OpenSearch by opensearch-project.
the class GeometryParserTests method testGeoJsonParsing.
public void testGeoJsonParsing() throws Exception {
XContentBuilder pointGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "Point").startArray("coordinates").value(100.0).value(0.0).endArray().endObject();
try (XContentParser parser = createParser(pointGeoJson)) {
parser.nextToken();
GeometryFormat format = new GeometryParser(true, randomBoolean(), randomBoolean()).geometryFormat(parser);
assertEquals(new Point(100, 0), format.fromXContent(parser));
XContentBuilder newGeoJson = XContentFactory.jsonBuilder();
format.toXContent(new Point(100, 10), newGeoJson, ToXContent.EMPTY_PARAMS);
assertEquals("{\"type\":\"Point\",\"coordinates\":[100.0,10.0]}", Strings.toString(newGeoJson));
}
XContentBuilder pointGeoJsonWithZ = XContentFactory.jsonBuilder().startObject().field("type", "Point").startArray("coordinates").value(100.0).value(0.0).value(10.0).endArray().endObject();
try (XContentParser parser = createParser(pointGeoJsonWithZ)) {
parser.nextToken();
assertEquals(new Point(100, 0, 10.0), new GeometryParser(true, randomBoolean(), true).parse(parser));
}
try (XContentParser parser = createParser(pointGeoJsonWithZ)) {
parser.nextToken();
expectThrows(IllegalArgumentException.class, () -> new GeometryParser(true, randomBoolean(), false).parse(parser));
}
XContentBuilder polygonGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "Polygon").startArray("coordinates").startArray().startArray().value(100.0).value(1.0).endArray().startArray().value(101.0).value(1.0).endArray().startArray().value(101.0).value(0.0).endArray().startArray().value(100.0).value(0.0).endArray().endArray().endArray().endObject();
Polygon p = new Polygon(new LinearRing(new double[] { 100d, 101d, 101d, 100d, 100d }, new double[] { 1d, 1d, 0d, 0d, 1d }));
try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken();
// Coerce should automatically close the polygon
assertEquals(p, new GeometryParser(true, true, randomBoolean()).parse(parser));
}
try (XContentParser parser = createParser(polygonGeoJson)) {
parser.nextToken();
// No coerce - the polygon parsing should fail
expectThrows(XContentParseException.class, () -> new GeometryParser(true, false, randomBoolean()).parse(parser));
}
}
Aggregations