LinestringGeometrySubsampler implements GeometryOperator { @Override public Geometry apply(Geometry geometry, Context context) { if (!(geometry instanceof LineString)) { return geometry; } if (context.getSubsampleCount() == null) { throw new IllegalStateException("subsampleCount must be set in the GeometryOperator.Context"); } int subsampleCount = context.getSubsampleCount(); Coordinate[] input = geometry.getCoordinates(); int inputSize = input.length; if (input.length <= subsampleCount) { return geometry; } Coordinate[] output = new Coordinate[subsampleCount]; for (int i = 0; i < subsampleCount; i++) { output[i] = input[i * inputSize / subsampleCount]; } return new GeometryFactory().createLineString(output); }  @Override Geometry apply(Geometry geometry, Context context);  }
@Test public void testBelowCount() throws ParseException { String wkt = generate(999); Geometry geometry = new WKTReader().read(wkt); LinestringGeometrySubsampler linestringGeometrySubsampler = new LinestringGeometrySubsampler(); GeometryOperator.Context context = new GeometryOperator.Context(); context.setSubsampleCount(1000); Geometry actual = linestringGeometrySubsampler.apply(geometry, context); assertThat(actual.getCoordinates().length, is(999)); }
@Test public void testAboveCount() throws ParseException { String wkt = generate(1001); Geometry geometry = new WKTReader().read(wkt); LinestringGeometrySubsampler linestringGeometrySubsampler = new LinestringGeometrySubsampler(); GeometryOperator.Context context = new GeometryOperator.Context(); context.setSubsampleCount(1000); Geometry actual = linestringGeometrySubsampler.apply(geometry, context); assertThat(actual.getCoordinates().length, is(1000)); }
@Test public void testNonLineString() throws ParseException { String wkt = "POLYGON (( 0 0, 1 1, 2 2, 0 0))"; Geometry geometry = new WKTReader().read(wkt); LinestringGeometrySubsampler linestringGeometrySubsampler = new LinestringGeometrySubsampler(); GeometryOperator.Context context = new GeometryOperator.Context(); context.setSubsampleCount(1000); Geometry actual = linestringGeometrySubsampler.apply(geometry, context); assertThat(actual, is(geometry)); }
@Test(expected = IllegalStateException.class) public void testNullSubsampleCount() throws ParseException { String wkt = generate(1001); Geometry geometry = new WKTReader().read(wkt); LinestringGeometrySubsampler linestringGeometrySubsampler = new LinestringGeometrySubsampler(); GeometryOperator.Context context = new GeometryOperator.Context(); context.setSubsampleCount(null); linestringGeometrySubsampler.apply(geometry, context); }