ConvertSubpolygonsToEnvelopes implements GeometryOperator { @Override public Geometry apply(Geometry geometry, Context context) { if (geometry == null || geometry.getNumGeometries() <= 1) { return geometry; } LOGGER.trace("Converting geometry: {}", geometry); Geometry[] envelopes = IntStream.range(0, geometry.getNumGeometries()) .mapToObj(geometry::getGeometryN) .map(Geometry::getEnvelope) .toArray(Geometry[]::new); Geometry envelopePolygons = GEOMETRY_FACTORY.createGeometryCollection(envelopes).union(); LOGGER.trace( "Converted geometry: {}\n isValid? {}", envelopePolygons, envelopePolygons.isValid()); return envelopePolygons.isValid() ? envelopePolygons : geometry; }  @Override Geometry apply(Geometry geometry, Context context);  }
@Test public void testNullSubpolygon() { Geometry geometry = null; Geometry actual = convertSubpolygonsToEnvelopes.apply(geometry, new GeometryOperator.Context()); assertThat(actual, nullValue()); }
@Test public void testEmptySubpolygon() { Geometry geometry = GEOMETRY_FACTORY.createMultiPolygon(null); Geometry actual = convertSubpolygonsToEnvelopes.apply(geometry, new GeometryOperator.Context()); assertThat(actual.isEmpty(), is(true)); }
@Test public void testSingleSubpolygon() throws ParseException { String wkt = "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"; WKTReader wktReader = new WKTReader(); Geometry geometry = wktReader.read(wkt); Geometry actual = convertSubpolygonsToEnvelopes.apply(geometry, new GeometryOperator.Context()); assertThat(actual, is(geometry)); }
@Test public void testTwoSubpolygons() throws ParseException { String wkt = "MULTIPOLYGON (((0 0, 2 10, 10 20, 20 20, 20 0, 0 0)),((0 40, 2 50, 10 60, 20 60, 20 40, 0 40)))"; WKTReader wktReader = new WKTReader(); Geometry geometry = wktReader.read(wkt); Geometry actual = convertSubpolygonsToEnvelopes.apply(geometry, new GeometryOperator.Context()); Geometry expected = wktReader.read( "MULTIPOLYGON (((0 0, 0 20, 20 20, 20 0, 0 0)), ((0 40, 0 60, 20 60, 20 40, 0 40)))"); assertThat(actual, is(expected)); }
@Test public void testGeometryCollection() throws ParseException { final String wkt = "GEOMETRYCOLLECTION (POINT (0 0), LINESTRING (10 10, 20 20), LINESTRING (20 20, 10 30))"; final WKTReader wktReader = new WKTReader(); final Geometry geometry = wktReader.read(wkt); final Geometry actual = convertSubpolygonsToEnvelopes.apply(geometry, new GeometryOperator.Context()); final Geometry expected = wktReader.read( "GEOMETRYCOLLECTION( POINT (0 0), POLYGON ((10 10, 10 20, 10 30, 20 30, 20 20, 20 10, 10 10)))"); assertThat(actual, is(expected)); }