You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ji...@apache.org on 2024/06/12 04:19:56 UTC
(sedona) branch master updated: [SEDONA-102] Use spotless as Java and Scala code formatter (#1428)
This is an automated email from the ASF dual-hosted git repository.
jiayu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sedona.git
The following commit(s) were added to refs/heads/master by this push:
new b69bc21b1 [SEDONA-102] Use spotless as Java and Scala code formatter (#1428)
b69bc21b1 is described below
commit b69bc21b1a5f0b9ce154533fc1e06130f80f3175
Author: Kristin Cowalcijk <ko...@apache.org>
AuthorDate: Wed Jun 12 12:19:52 2024 +0800
[SEDONA-102] Use spotless as Java and Scala code formatter (#1428)
* Add spotless
* mvn spotless:apply
---
.pre-commit-config.yaml | 8 +-
LICENSE | 3 +-
.../org/apache/sedona/common/Constructors.java | 480 +-
.../java/org/apache/sedona/common/Functions.java | 3824 ++++++------
.../apache/sedona/common/FunctionsGeoTools.java | 297 +-
.../java/org/apache/sedona/common/Predicates.java | 152 +-
.../sedona/common/enums/FileDataSplitter.java | 148 +-
.../apache/sedona/common/enums/GeometryType.java | 54 +-
.../sedona/common/geometryObjects/Circle.java | 920 +--
.../geometrySerde/ByteBufferGeometryBuffer.java | 408 +-
.../common/geometrySerde/CoordinateType.java | 59 +-
.../common/geometrySerde/GeometryBuffer.java | 35 +-
.../geometrySerde/GeometryBufferFactory.java | 69 +-
.../sedona/common/geometrySerde/GeometrySerde.java | 234 +-
.../common/geometrySerde/GeometrySerializer.java | 1079 ++--
.../common/geometrySerde/SpatialIndexSerde.java | 159 +-
.../common/geometrySerde/UnsafeGeometryBuffer.java | 514 +-
.../common/raster/DeepCopiedRenderedImage.java | 928 +--
.../sedona/common/raster/GeometryFunctions.java | 208 +-
.../apache/sedona/common/raster/MapAlgebra.java | 1075 ++--
.../sedona/common/raster/PixelFunctionEditors.java | 423 +-
.../sedona/common/raster/PixelFunctions.java | 476 +-
.../apache/sedona/common/raster/PixelRecord.java | 18 +-
.../sedona/common/raster/RasterAccessors.java | 456 +-
.../sedona/common/raster/RasterBandAccessors.java | 892 +--
.../sedona/common/raster/RasterBandEditors.java | 673 +-
.../sedona/common/raster/RasterConstructors.java | 1248 ++--
.../raster/RasterConstructorsForTesting.java | 375 +-
.../apache/sedona/common/raster/RasterEditors.java | 1043 ++--
.../apache/sedona/common/raster/RasterOutputs.java | 621 +-
.../sedona/common/raster/RasterPredicates.java | 287 +-
.../inputstream/ByteArrayImageInputStream.java | 88 +-
.../common/raster/netcdf/NetCdfConstants.java | 44 +-
.../sedona/common/raster/netcdf/NetCdfReader.java | 681 ++-
.../common/raster/serde/AWTRasterSerializer.java | 51 +-
.../raster/serde/AffineTransform2DSerializer.java | 71 +-
.../sedona/common/raster/serde/CRSSerializer.java | 178 +-
.../common/raster/serde/DataBufferSerializer.java | 139 +-
.../raster/serde/GridEnvelopeSerializer.java | 59 +-
.../serde/GridSampleDimensionSerializer.java | 81 +-
.../sedona/common/raster/serde/KryoUtil.java | 520 +-
.../common/raster/serde/SampleModelSerializer.java | 279 +-
.../apache/sedona/common/raster/serde/Serde.java | 310 +-
.../sedona/common/simplify/BaseSimplifier.java | 31 +-
.../sedona/common/simplify/CircleSimplifier.java | 35 +-
.../sedona/common/simplify/CoordinateSplitter.java | 152 +-
.../common/simplify/CoordinatesSimplifier.java | 112 +-
.../simplify/GeometryCollectionSimplifier.java | 113 +-
.../sedona/common/simplify/GeometrySimplifier.java | 54 +-
.../common/simplify/LineStringSimplifier.java | 55 +-
.../sedona/common/simplify/PolygonSimplifier.java | 78 +-
.../simplify/ZeroToleranceGeometrySimplifier.java | 90 +-
.../org/apache/sedona/common/sphere/Haversine.java | 154 +-
.../org/apache/sedona/common/sphere/Spheroid.java | 250 +-
.../common/subDivide/GeometrySubDivider.java | 282 +-
.../sedona/common/subDivide/PivotFinder.java | 101 +-
.../apache/sedona/common/subDivide/SubBoxes.java | 53 +-
.../sedona/common/subDivide/SubDivideExtent.java | 123 +-
.../java/org/apache/sedona/common/utils/BBox.java | 55 +-
.../common/utils/CachedCRSTransformFinder.java | 84 +-
.../apache/sedona/common/utils/FormatUtils.java | 623 +-
.../apache/sedona/common/utils/GeoHashDecoder.java | 130 +-
.../org/apache/sedona/common/utils/GeomUtils.java | 1235 ++--
.../common/utils/GeometryForce3DMTransformer.java | 70 +-
.../common/utils/GeometryForce4DTransformer.java | 88 +-
.../common/utils/GeometryGeoHashEncoder.java | 11 +-
.../common/utils/GeometryLocateAlongProcessor.java | 238 +-
.../sedona/common/utils/GeometrySplitter.java | 536 +-
.../org/apache/sedona/common/utils/H3Utils.java | 485 +-
.../sedona/common/utils/HalfOpenRectangle.java | 38 +-
.../org/apache/sedona/common/utils/ImageUtils.java | 84 +-
.../sedona/common/utils/PointGeoHashEncoder.java | 119 +-
.../sedona/common/utils/RasterInterpolate.java | 247 +-
.../apache/sedona/common/utils/RasterUtils.java | 1696 +++---
.../org/apache/sedona/common/utils/S2Utils.java | 154 +-
.../sedona/common/utils/TelemetryCollector.java | 75 +-
.../apache/sedona/common/utils/ValidDetail.java | 30 +-
.../jts/index/quadtree/IndexSerde.java | 163 +-
.../locationtech/jts/index/strtree/IndexSerde.java | 224 +-
.../java/org/apache/sedona/common/CircleTest.java | 397 +-
.../org/apache/sedona/common/ConstructorsTest.java | 446 +-
.../org/apache/sedona/common/FunctionsTest.java | 6409 +++++++++++---------
.../org/apache/sedona/common/GeometryUtilTest.java | 99 +-
.../java/org/apache/sedona/common/H3UtilTest.java | 476 +-
.../org/apache/sedona/common/PredicatesTest.java | 281 +-
.../java/org/apache/sedona/common/S2UtilTest.java | 184 +-
.../java/org/apache/sedona/common/TestBase.java | 25 +-
.../common/geometrySerde/GeometryBufferTest.java | 456 +-
.../geometrySerde/GeometryCollectionSerdeTest.java | 191 +-
.../common/geometrySerde/LineStringSerdeTest.java | 225 +-
.../geometrySerde/MultiLineStringSerdeTest.java | 99 +-
.../common/geometrySerde/MultiPointSerdeTest.java | 180 +-
.../geometrySerde/MultiPolygonSerdeTest.java | 137 +-
.../common/geometrySerde/PointSerdeTest.java | 151 +-
.../common/geometrySerde/PolygonSerdeTest.java | 135 +-
.../geometrySerde/SpatialIndexSerdeTest.java | 340 +-
.../sedona/common/raster/FunctionEditorsTest.java | 350 +-
.../apache/sedona/common/raster/FunctionsTest.java | 739 +--
.../common/raster/GeometryFunctionsTest.java | 253 +-
.../sedona/common/raster/MapAlgebraTest.java | 1161 ++--
.../sedona/common/raster/RasterAccessorsTest.java | 793 +--
.../common/raster/RasterBandAccessorsTest.java | 1054 ++--
.../common/raster/RasterBandEditorsTest.java | 816 +--
.../raster/RasterConstructorsForTestingTest.java | 182 +-
.../common/raster/RasterConstructorsTest.java | 1073 ++--
.../sedona/common/raster/RasterEditorsTest.java | 4794 +++++++++++++--
.../sedona/common/raster/RasterOutputTest.java | 398 +-
.../sedona/common/raster/RasterPredicatesTest.java | 907 +--
.../sedona/common/raster/RasterTestBase.java | 324 +-
.../common/raster/serde/CRSSerializerTest.java | 30 +-
.../raster/serde/DataBufferSerializerTest.java | 252 +-
.../raster/serde/KryoSerializerTestBase.java | 47 +-
.../sedona/common/raster/serde/KryoUtilTest.java | 410 +-
.../raster/serde/SampleModelSerializerTest.java | 178 +-
.../sedona/common/raster/serde/SerdeTest.java | 103 +-
.../common/sphere/HaversineEnvelopeTest.java | 496 +-
.../sedona/common/telemetry/TelemetryTest.java | 13 +-
.../sedona/common/utils/RasterUtilsTest.java | 191 +-
docs/community/rule.md | 2 +
.../main/java/org/apache/sedona/flink/Catalog.java | 423 +-
.../org/apache/sedona/flink/SedonaContext.java | 67 +-
.../sedona/flink/SedonaFlinkRegistrator.java | 96 +-
.../sedona/flink/expressions/Accumulators.java | 88 +-
.../sedona/flink/expressions/Aggregators.java | 318 +-
.../sedona/flink/expressions/Constructors.java | 868 +--
.../apache/sedona/flink/expressions/Functions.java | 2568 ++++----
.../flink/expressions/FunctionsGeoTools.java | 79 +-
.../sedona/flink/expressions/Predicates.java | 525 +-
.../java/org/apache/sedona/flink/AdapterTest.java | 62 +-
.../org/apache/sedona/flink/AggregatorTest.java | 142 +-
.../org/apache/sedona/flink/ConstructorTest.java | 1417 +++--
.../java/org/apache/sedona/flink/FunctionTest.java | 4155 +++++++------
.../org/apache/sedona/flink/PredicateTest.java | 371 +-
.../java/org/apache/sedona/flink/TestBase.java | 849 +--
pom.xml | 33 +
.../sedona/snowflake/snowsql/GeoToolsWrapper.java | 63 +-
.../sedona/snowflake/snowsql/GeometrySerde.java | 122 +-
.../apache/sedona/snowflake/snowsql/TypeUtils.java | 55 +-
.../org/apache/sedona/snowflake/snowsql/UDFs.java | 2935 ++++-----
.../apache/sedona/snowflake/snowsql/UDFsV2.java | 2890 +++++----
.../snowsql/annotations/UDFAnnotations.java | 82 +-
.../snowsql/annotations/UDTFAnnotations.java | 82 +-
.../snowflake/snowsql/ddl/ArgSpecBuilder.java | 122 +-
.../sedona/snowflake/snowsql/ddl/Constants.java | 71 +-
.../sedona/snowflake/snowsql/ddl/DDLGenerator.java | 204 +-
.../snowflake/snowsql/ddl/UDFDDLGenerator.java | 264 +-
.../snowflake/snowsql/ddl/UDTFDDLGenerator.java | 263 +-
.../sedona/snowflake/snowsql/udtfs/ST_Collect.java | 86 +-
.../sedona/snowflake/snowsql/udtfs/ST_Dump.java | 61 +-
.../snowflake/snowsql/udtfs/ST_Envelope_Aggr.java | 101 +-
.../snowsql/udtfs/ST_Intersection_Aggr.java | 81 +-
.../snowflake/snowsql/udtfs/ST_IsValidDetail.java | 74 +-
.../snowsql/udtfs/ST_MinimumBoundingRadius.java | 86 +-
.../snowsql/udtfs/ST_SubDivideExplode.java | 68 +-
.../snowsql/udtfs/ST_SubDivideExplodeV2.java | 82 +-
.../snowflake/snowsql/udtfs/ST_Union_Aggr.java | 83 +-
.../org/apache/sedona/core/enums/GridType.java | 69 +-
.../org/apache/sedona/core/enums/IndexType.java | 46 +-
.../apache/sedona/core/enums/JoinBuildSide.java | 27 +-
.../core/enums/JoinSparitionDominantSide.java | 23 +-
.../core/enums/SpatialJoinOptimizationMode.java | 56 +-
.../core/formatMapper/EarthdataHDFPointMapper.java | 417 +-
.../sedona/core/formatMapper/FormatMapper.java | 99 +-
.../sedona/core/formatMapper/GeoJsonReader.java | 120 +-
.../core/formatMapper/LineStringFormatMapper.java | 49 +-
.../core/formatMapper/PointFormatMapper.java | 46 +-
.../core/formatMapper/PolygonFormatMapper.java | 49 +-
.../apache/sedona/core/formatMapper/RddReader.java | 18 +-
.../core/formatMapper/RectangleFormatMapper.java | 47 +-
.../apache/sedona/core/formatMapper/WkbReader.java | 86 +-
.../apache/sedona/core/formatMapper/WktReader.java | 86 +-
.../netcdfParser/HDFSRandomAccessFile.java | 156 +-
.../formatMapper/netcdfParser/SerNetCDFUtils.java | 300 +-
.../formatMapper/shapefileParser/ShapefileRDD.java | 404 +-
.../shapefileParser/ShapefileReader.java | 613 +-
.../shapefileParser/boundary/BoundBox.java | 394 +-
.../boundary/BoundaryInputFormat.java | 119 +-
.../boundary/BoundaryRecordReader.java | 139 +-
.../fieldname/FieldnameInputFormat.java | 119 +-
.../fieldname/FieldnameRecordReader.java | 166 +-
.../parseUtils/dbf/DbfParseUtil.java | 363 +-
.../parseUtils/dbf/FieldDescriptor.java | 193 +-
.../parseUtils/shp/MultiPointParser.java | 56 +-
.../parseUtils/shp/PointParser.java | 54 +-
.../parseUtils/shp/PolyLineParser.java | 74 +-
.../parseUtils/shp/PolygonParser.java | 144 +-
.../parseUtils/shp/ShapeFileConst.java | 80 +-
.../parseUtils/shp/ShapeParser.java | 98 +-
.../parseUtils/shp/ShapeReader.java | 12 +-
.../parseUtils/shp/ShapeReaderFactory.java | 110 +-
.../shapefileParser/parseUtils/shp/ShapeSerde.java | 378 +-
.../shapefileParser/parseUtils/shp/ShapeType.java | 160 +-
.../parseUtils/shp/ShpFileParser.java | 249 +-
.../parseUtils/shp/TypeUnknownException.java | 26 +-
.../shapefileParser/shapes/CombineShapeReader.java | 284 +-
.../shapefileParser/shapes/DbfFileReader.java | 116 +-
.../shapefileParser/shapes/PrimitiveShape.java | 79 +-
.../shapefileParser/shapes/ShapeFileReader.java | 181 +-
.../shapefileParser/shapes/ShapeInputFormat.java | 163 +-
.../shapefileParser/shapes/ShapeKey.java | 33 +-
.../shapefileParser/shapes/ShpRecord.java | 76 +-
.../sedona/core/joinJudgement/DedupParams.java | 32 +-
.../core/joinJudgement/DuplicatesFilter.java | 55 +-
.../joinJudgement/DynamicIndexLookupJudgement.java | 184 +-
.../sedona/core/joinJudgement/JudgementBase.java | 472 +-
.../joinJudgement/LeftIndexLookupJudgement.java | 94 +-
.../core/joinJudgement/NestedLoopJudgement.java | 101 +-
.../joinJudgement/RightIndexLookupJudgement.java | 94 +-
.../knnJudgement/GeometryDistanceComparator.java | 91 +-
.../sedona/core/knnJudgement/KnnJudgement.java | 108 +-
.../core/knnJudgement/KnnJudgementUsingIndex.java | 91 +-
.../sedona/core/rangeJudgement/JudgementBase.java | 79 +-
.../sedona/core/rangeJudgement/RangeFilter.java | 36 +-
.../core/rangeJudgement/RangeFilterUsingIndex.java | 75 +-
.../sedona/core/serde/SedonaKryoRegistrator.java | 44 +-
.../showcase/EarthdataMapperRunnableExample.java | 271 +-
.../org/apache/sedona/core/showcase/Example.java | 594 +-
.../showcase/UserSuppliedLineStringMapper.java | 113 +-
.../core/showcase/UserSuppliedPointMapper.java | 61 +-
.../core/showcase/UserSuppliedPolygonMapper.java | 119 +-
.../core/showcase/UserSuppliedRectangleMapper.java | 113 +-
.../sedona/core/spatialOperator/JoinQuery.java | 1226 ++--
.../sedona/core/spatialOperator/KNNQuery.java | 89 +-
.../sedona/core/spatialOperator/RangeQuery.java | 284 +-
.../core/spatialOperator/SpatialPredicate.java | 62 +-
.../SpatialPredicateEvaluators.java | 217 +-
.../spatialPartitioning/EqualPartitioning.java | 204 +-
.../spatialPartitioning/FlatGridPartitioner.java | 104 +-
.../spatialPartitioning/HilbertPartitioning.java | 342 +-
.../sedona/core/spatialPartitioning/KDB.java | 589 +-
.../spatialPartitioning/KDBTreePartitioner.java | 62 +-
.../spatialPartitioning/PartitioningUtils.java | 183 +-
.../spatialPartitioning/QuadTreePartitioner.java | 73 +-
.../spatialPartitioning/QuadtreePartitioning.java | 75 +-
.../spatialPartitioning/RtreePartitioning.java | 149 +-
.../spatialPartitioning/SpatialPartitioner.java | 75 +-
.../spatialPartitioning/VoronoiPartitioning.java | 96 +-
.../spatialPartitioning/quadtree/QuadNode.java | 27 +-
.../quadtree/QuadRectangle.java | 177 +-
.../quadtree/StandardQuadTree.java | 810 ++-
.../apache/sedona/core/spatialRDD/CircleRDD.java | 218 +-
.../sedona/core/spatialRDD/LineStringRDD.java | 229 +-
.../apache/sedona/core/spatialRDD/PointRDD.java | 219 +-
.../apache/sedona/core/spatialRDD/PolygonRDD.java | 274 +-
.../sedona/core/spatialRDD/RectangleRDD.java | 216 +-
.../apache/sedona/core/spatialRDD/SpatialRDD.java | 1055 ++--
.../sedona/core/spatialRddTool/IndexBuilder.java | 55 +-
.../sedona/core/spatialRddTool/StatCalculator.java | 108 +-
.../apache/sedona/core/utils/RDDSampleUtils.java | 89 +-
.../org/apache/sedona/core/utils/SedonaConf.java | 251 +-
.../org/apache/sedona/core/utils/TimeUtils.java | 11 +-
.../apache/sedona/viz/core/BigBufferedImage.java | 799 ++-
.../org/apache/sedona/viz/core/ColoringRule.java | 28 +-
.../apache/sedona/viz/core/GlobalParameter.java | 761 ++-
.../org/apache/sedona/viz/core/ImageGenerator.java | 728 ++-
.../sedona/viz/core/ImageSerializableWrapper.java | 126 +-
.../org/apache/sedona/viz/core/ImageStitcher.java | 448 +-
.../org/apache/sedona/viz/core/PhotoFilter.java | 72 +-
.../sedona/viz/core/RasterOverlayOperator.java | 240 +-
.../viz/core/Serde/ImageWrapperSerializer.java | 102 +-
.../sedona/viz/core/Serde/PixelSerializer.java | 67 +-
.../viz/core/Serde/SedonaVizKryoRegistrator.java | 27 +-
.../sedona/viz/core/VectorOverlayOperator.java | 182 +-
.../sedona/viz/core/VisualizationOperator.java | 1704 +++---
.../sedona/viz/core/VisualizationPartitioner.java | 398 +-
.../coloringRule/ColoringRuleFactory.java | 46 +-
.../coloringRule/GenericColoringRule.java | 68 +-
.../viz/extension/coloringRule/LinearFunction.java | 69 +-
.../extension/coloringRule/PiecewiseFunction.java | 84 +-
.../imageGenerator/SedonaVizImageGenerator.java | 740 +--
.../sedona/viz/extension/photoFilter/BoxBlur.java | 33 +-
.../sedona/viz/extension/photoFilter/Embose.java | 37 +-
.../viz/extension/photoFilter/GaussianBlur.java | 55 +-
.../sedona/viz/extension/photoFilter/Outline.java | 37 +-
.../sedona/viz/extension/photoFilter/Sharpen.java | 37 +-
.../visualizationEffect/ChoroplethMap.java | 330 +-
.../viz/extension/visualizationEffect/HeatMap.java | 231 +-
.../extension/visualizationEffect/ScatterPlot.java | 372 +-
.../org/apache/sedona/viz/showcase/Example.java | 781 +--
.../apache/sedona/viz/utils/ColorizeOption.java | 108 +-
.../org/apache/sedona/viz/utils/ImageType.java | 108 +-
.../java/org/apache/sedona/viz/utils/Pixel.java | 284 +-
.../sedona/viz/utils/RasterizationUtils.java | 925 +--
.../org/apache/sedona/viz/utils/S3Operator.java | 105 +-
.../apache/sedona/core/monitoring/Listener.scala | 35 +-
.../apache/sedona/core/monitoring/Metrics.scala | 1 -
.../ScalaEarthdataMapperRunnableExample.scala | 33 +-
.../apache/sedona/core/showcase/ScalaExample.scala | 152 +-
.../python/wrapper/SerializationException.scala | 8 +-
.../python/wrapper/adapters/EnvelopeAdapter.scala | 16 +-
.../python/wrapper/adapters/GeomSerializer.scala | 1 -
.../python/wrapper/adapters/GeometryAdapter.scala | 1 -
.../wrapper/adapters/JoinParamsAdapter.scala | 7 +-
.../python/wrapper/adapters/PythonConverter.scala | 7 +-
.../adapters/PythonRddToJavaRDDAdapter.scala | 39 +-
.../wrapper/adapters/RawJvmIndexRDDAdapter.scala | 6 +-
.../adapters/SpatialObjectLoaderAdapter.scala | 2 -
.../wrapper/translation/CircleSerializer.scala | 5 +-
.../wrapper/translation/FlatPairRddConverter.scala | 27 +-
.../wrapper/translation/GeometryRddConverter.scala | 19 +-
.../translation/GeometrySeqToPythonConverter.scala | 11 +-
.../wrapper/translation/GeometrySerializer.scala | 2 -
.../wrapper/translation/ListPairRddConverter.scala | 29 +-
.../translation/PythonGeometrySerializer.scala | 5 +-
.../translation/PythonRDDToJavaConverter.scala | 18 +-
.../translation/PythonRddToJavaRDDConverter.scala | 38 +-
.../wrapper/translation/RDDToPythonConverter.scala | 1 -
.../wrapper/utils/PythonAdapterWrapper.scala | 25 +-
.../sedona/python/wrapper/utils/implicits.scala | 1 -
.../org/apache/sedona/spark/SedonaContext.scala | 46 +-
.../org/apache/sedona/sql/RasterRegistrator.scala | 7 +-
.../apache/sedona/sql/SedonaSqlExtensions.scala | 1 -
.../scala/org/apache/sedona/sql/UDF/Catalog.scala | 23 +-
.../apache/sedona/sql/UDF/RasterUdafCatalog.scala | 4 +-
.../org/apache/sedona/sql/UDF/UdfRegistrator.scala | 11 +-
.../org/apache/sedona/sql/utils/Adapter.scala | 272 +-
.../sql/utils/GeoToolsCoverageAvailability.scala | 3 +-
.../sedona/sql/utils/GeometrySerializer.scala | 28 +-
.../apache/sedona/sql/utils/RasterSerializer.scala | 14 +-
.../apache/sedona/viz/showcase/ScalaExample.scala | 226 +-
.../sedona/viz/sql/SedonaVizExtensions.scala | 1 -
.../org/apache/sedona/viz/sql/UDF/Catalog.scala | 12 +-
.../apache/sedona/viz/sql/UDF/UdfRegistrator.scala | 18 +-
.../sql/operator/AggregateWithinPartitons.scala | 77 +-
.../sedona/viz/sql/operator/VizPartitioner.scala | 44 +-
.../parquet/GeoParquetFileFormatBase.scala | 40 +-
.../datasources/parquet/GeoParquetMetaData.scala | 93 +-
.../parquet/GeoParquetSpatialFilter.scala | 59 +-
.../spark/sql/sedona_sql/UDT/GeometryUDT.scala | 6 +-
.../spark/sql/sedona_sql/UDT/RasterUDT.scala | 1 -
.../UDT/RasterUdtRegistratorWrapper.scala | 6 +-
.../expressions/AggregateFunctions.scala | 39 +-
.../sql/sedona_sql/expressions/Constructors.scala | 215 +-
.../sql/sedona_sql/expressions/DataFrameAPI.scala | 13 +-
.../expressions/FoldableExpression.scala | 6 +-
.../sql/sedona_sql/expressions/Functions.scala | 775 +--
.../expressions/InferrableFunctionConverter.scala | 2190 ++++---
.../expressions/InferredExpression.scala | 226 +-
.../expressions/InferredRasterExpression.scala | 12 +-
.../sql/sedona_sql/expressions/Predicates.scala | 124 +-
.../expressions/collect/ST_Collect.scala | 1 -
.../sql/sedona_sql/expressions/implicits.scala | 9 +-
.../expressions/raster/AggregateFunctions.scala | 48 +-
.../expressions/raster/GeometryFunctions.scala | 11 +-
.../sql/sedona_sql/expressions/raster/IO.scala | 12 +-
.../sedona_sql/expressions/raster/MapAlgebra.scala | 80 +-
.../expressions/raster/PixelFunctionEditors.scala | 19 +-
.../expressions/raster/PixelFunctions.scala | 87 +-
.../expressions/raster/RasterAccessors.scala | 72 +-
.../expressions/raster/RasterBandAccessors.scala | 71 +-
.../expressions/raster/RasterBandEditors.scala | 42 +-
.../expressions/raster/RasterConstructors.scala | 68 +-
.../expressions/raster/RasterEditors.scala | 46 +-
.../expressions/raster/RasterOutputs.scala | 34 +-
.../expressions/raster/RasterPredicates.scala | 25 +-
.../sedona_sql/expressions/raster/implicits.scala | 5 +-
.../sedona_sql/expressions/st_constructors.scala | 178 +-
.../sql/sedona_sql/expressions/st_functions.scala | 592 +-
.../sql/sedona_sql/expressions/st_predicates.scala | 18 +-
.../sedona_sql/io/geojson/GeoJSONFileFormat.scala | 98 +-
.../io/geojson/GeoJSONJacksonGenerator.scala | 123 +-
.../io/geojson/GeoJSONOutputWriter.scala | 46 +-
.../sql/sedona_sql/io/geojson/GeoJSONUtils.scala | 44 +-
.../sedona_sql/io/geojson/SparkCompatUtil.scala | 123 +-
.../sedona_sql/io/raster/RasterFileFormat.scala | 48 +-
.../sql/sedona_sql/io/raster/RasterOptions.scala | 3 +-
.../sedona_sql/optimization/ExpressionUtils.scala | 34 +-
.../SpatialFilterPushDownForGeoParquet.scala | 32 +-
.../strategy/join/BroadcastIndexJoinExec.scala | 123 +-
.../strategy/join/DistanceJoinExec.scala | 73 +-
.../strategy/join/JoinQueryDetector.scala | 641 +-
.../sedona_sql/strategy/join/JoinedGeometry.scala | 24 +-
.../strategy/join/JoinedGeometryRaster.scala | 17 +-
.../strategy/join/OptimizableJoinCondition.scala | 42 +-
.../sedona_sql/strategy/join/RangeJoinExec.scala | 42 +-
.../strategy/join/SpatialIndexExec.scala | 34 +-
.../strategy/join/TraitJoinQueryBase.scala | 47 +-
.../strategy/join/TraitJoinQueryExec.scala | 83 +-
.../sql/sedona_viz/UDT/UdtRegistratorWrapper.scala | 4 +-
.../sql/sedona_viz/expressions/Colorize.scala | 20 +-
.../sql/sedona_viz/expressions/ImageEncoder.scala | 3 +-
.../sql/sedona_viz/expressions/Partitioner.scala | 3 +-
.../sql/sedona_viz/expressions/Pixelize.scala | 54 +-
.../spark/sql/sedona_viz/expressions/Render.scala | 8 +-
.../test/java/org/apache/sedona/core/TestBase.java | 40 +-
.../sedona/core/formatMapper/GeoJsonIOTest.java | 293 +-
.../TestReadInvalidSyntaxGeometriesTest.java | 75 +-
.../sedona/core/formatMapper/WkbReadTest.java | 67 +-
.../sedona/core/formatMapper/WktReaderTest.java | 68 +-
.../shapefileParser/shapes/GeometrySerdeTest.java | 102 +-
.../shapefileParser/shapes/ShapefileRDDTest.java | 585 +-
.../shapes/ShapefileReaderTest.java | 644 +-
.../sedona/core/formatMapper/testSerNetCDF.java | 93 +-
.../apache/sedona/core/io/EarthdataHDFTest.java | 251 +-
.../JoinQueryCorrectnessChecker.java | 840 ++-
.../JoinQueryDeduplicationTest.java | 73 +-
.../sedona/core/spatialOperator/JoinQueryTest.java | 565 +-
.../sedona/core/spatialOperator/JoinTestBase.java | 275 +-
.../core/spatialOperator/LineStringKnnTest.java | 277 +-
.../core/spatialOperator/LineStringRangeTest.java | 287 +-
.../sedona/core/spatialOperator/PointKnnTest.java | 368 +-
.../core/spatialOperator/PointRangeTest.java | 266 +-
.../core/spatialOperator/PolygonKnnTest.java | 349 +-
.../core/spatialOperator/PolygonRangeTest.java | 284 +-
.../core/spatialOperator/RangeQueryTest.java | 176 +-
.../core/spatialOperator/RectangleKnnTest.java | 345 +-
.../core/spatialOperator/RectangleRangeTest.java | 337 +-
.../core/spatialOperator/SpatialQueryTestBase.java | 181 +-
.../quadtree/QuadRectangleTest.java | 43 +-
.../quadtree/QuadTreePanel.java | 103 +-
.../quadtree/QuadTreePartitioningTest.java | 48 +-
.../spatialPartitioning/quadtree/QuadTreeTest.java | 299 +-
.../quadtree/RenderQuadTree.java | 141 +-
.../core/spatialRDD/BoundaryAggregationTest.java | 243 +-
.../BoundaryAndCountAggregationTest.java | 81 +-
.../sedona/core/spatialRDD/GeometryOpTest.java | 112 +-
.../sedona/core/spatialRDD/LineStringRDDTest.java | 232 +-
.../sedona/core/spatialRDD/PointRDDTest.java | 208 +-
.../sedona/core/spatialRDD/PolygonRDDTest.java | 419 +-
.../sedona/core/spatialRDD/RectangleRDDTest.java | 186 +-
.../sedona/core/spatialRDD/SpatialRDDTestBase.java | 149 +-
.../core/spatialRDD/SpatialRDDWriterTest.java | 221 +-
.../sedona/core/utils/CRSTransformationTest.java | 290 +-
.../sedona/core/utils/RDDSampleUtilsTest.java | 80 +-
.../apache/sedona/core/utils/SedonaConfTest.java | 65 +-
.../org/apache/sedona/core/utils/testGeoJSON.java | 85 +-
.../org/apache/sedona/sql/adapterTestJava.java | 419 +-
.../org/apache/sedona/viz/ChoroplethmapTest.java | 203 +-
.../java/org/apache/sedona/viz/HeatmapTest.java | 152 +-
.../org/apache/sedona/viz/NYCTripPointMapper.java | 71 +-
.../java/org/apache/sedona/viz/NYCTripTest.java | 416 +-
.../sedona/viz/ParallelVisualizationTest.java | 341 +-
.../org/apache/sedona/viz/ScatterplotTest.java | 405 +-
.../java/org/apache/sedona/viz/VizTestBase.java | 310 +-
.../scala/org/apache/sedona/core/scalaTest.scala | 120 +-
.../python/wrapper/TestToPythonSerialization.scala | 79 +-
.../sedona/sql/BroadcastIndexJoinSuite.scala | 2166 +++++--
.../org/apache/sedona/sql/DeduplicationSuite.scala | 6 +-
.../org/apache/sedona/sql/GeometrySample.scala | 6 +-
.../apache/sedona/sql/GeometryUdtTestScala.scala | 6 +-
.../org/apache/sedona/sql/RasterJoinSuite.scala | 117 +-
.../org/apache/sedona/sql/SpatialJoinSuite.scala | 139 +-
.../sedona/sql/SphereDistanceJoinSuite.scala | 45 +-
.../org/apache/sedona/sql/TestBaseScala.scala | 229 +-
.../org/apache/sedona/sql/adapterTestScala.scala | 287 +-
.../sedona/sql/aggregateFunctionTestScala.scala | 41 +-
.../apache/sedona/sql/constructorTestScala.scala | 242 +-
.../apache/sedona/sql/dataFrameAPITestScala.scala | 842 ++-
.../org/apache/sedona/sql/functionTestScala.scala | 1912 ++++--
.../sedona/sql/functions/FunctionsHelper.scala | 1 -
.../sedona/sql/functions/STH3Functions.scala | 101 +-
.../apache/sedona/sql/functions/STS2CellIDs.scala | 72 +-
.../sedona/sql/functions/StMakePolygonSpec.scala | 80 +-
.../sql/functions/TestGeometrySimplify.scala | 84 +-
.../sedona/sql/functions/TestStSubDivide.scala | 69 +-
.../sql/functions/collect/TestStCollect.scala | 132 +-
.../sedona/sql/functions/geohash/Fixtures.scala | 78 +-
.../functions/geohash/TestCalculatingGeoHash.scala | 9 +-
.../sql/functions/geohash/TestGeoHashDecoder.scala | 9 +-
.../sql/functions/geohash/TestStGeoHash.scala | 126 +-
.../geohash/TestStGeometryFromGeoHash.scala | 57 +-
.../org/apache/sedona/sql/geojsonIOTests.scala | 215 +-
.../scala/org/apache/sedona/sql/implicits.scala | 7 +-
.../ogc/GeometryTypesAndFunctionsTestScala.scala | 449 +-
.../apache/sedona/sql/predicateJoinTestScala.scala | 637 +-
.../org/apache/sedona/sql/predicateTestScala.scala | 206 +-
.../scala/org/apache/sedona/sql/rasterIOTest.scala | 135 +-
.../org/apache/sedona/sql/rasteralgebraTest.scala | 1378 +++--
.../org/apache/sedona/sql/serdeAwareTest.scala | 45 +-
.../org/apache/sedona/viz/sql/VizTestBase.scala | 27 +-
.../apache/sedona/viz/sql/optVizOperatorTest.scala | 18 +-
.../sedona/viz/sql/standardVizOperatorTest.scala | 101 +-
.../datasources/parquet/GeoDataSourceUtils.scala | 140 +-
.../datasources/parquet/GeoDateTimeUtils.scala | 31 +-
.../datasources/parquet/GeoParquetFileFormat.scala | 180 +-
.../datasources/parquet/GeoParquetFilters.scala | 308 +-
.../parquet/GeoParquetReadSupport.scala | 194 +-
.../parquet/GeoParquetRecordMaterializer.scala | 67 +-
.../parquet/GeoParquetRowConverter.scala | 257 +-
.../parquet/GeoParquetSchemaConverter.scala | 133 +-
.../datasources/parquet/GeoParquetUtils.scala | 84 +-
.../parquet/GeoParquetWriteSupport.scala | 91 +-
.../datasources/parquet/GeoSchemaMergeUtils.scala | 57 +-
.../metadata/GeoParquetMetadataDataSource.scala | 42 +-
.../GeoParquetMetadataPartitionReaderFactory.scala | 56 +-
.../metadata/GeoParquetMetadataScan.scala | 38 +-
.../metadata/GeoParquetMetadataScanBuilder.scala | 25 +-
.../metadata/GeoParquetMetadataTable.scala | 52 +-
.../sedona/sql/GeoParquetMetadataTests.scala | 77 +-
.../sql/GeoParquetSpatialFilterPushDownSuite.scala | 235 +-
.../org/apache/sedona/sql/TestBaseScala.scala | 10 +-
.../org/apache/sedona/sql/geoparquetIOTests.scala | 219 +-
.../datasources/parquet/GeoDataSourceUtils.scala | 140 +-
.../datasources/parquet/GeoParquetFileFormat.scala | 184 +-
.../parquet/GeoParquetReadSupport.scala | 105 +-
.../parquet/GeoParquetRecordMaterializer.scala | 67 +-
.../parquet/GeoParquetRowConverter.scala | 257 +-
.../parquet/GeoParquetSchemaConverter.scala | 133 +-
.../datasources/parquet/GeoParquetUtils.scala | 84 +-
.../parquet/GeoParquetWriteSupport.scala | 91 +-
.../metadata/GeoParquetMetadataDataSource.scala | 42 +-
.../GeoParquetMetadataPartitionReaderFactory.scala | 56 +-
.../metadata/GeoParquetMetadataScan.scala | 39 +-
.../metadata/GeoParquetMetadataScanBuilder.scala | 25 +-
.../metadata/GeoParquetMetadataTable.scala | 52 +-
.../sedona/sql/GeoParquetMetadataTests.scala | 77 +-
.../sql/GeoParquetSpatialFilterPushDownSuite.scala | 235 +-
.../org/apache/sedona/sql/TestBaseScala.scala | 10 +-
.../org/apache/sedona/sql/geoparquetIOTests.scala | 219 +-
.../datasources/parquet/GeoParquetFileFormat.scala | 181 +-
.../parquet/GeoParquetReadSupport.scala | 79 +-
.../parquet/GeoParquetRecordMaterializer.scala | 67 +-
.../parquet/GeoParquetRowConverter.scala | 258 +-
.../parquet/GeoParquetSchemaConverter.scala | 133 +-
.../datasources/parquet/GeoParquetUtils.scala | 84 +-
.../parquet/GeoParquetWriteSupport.scala | 99 +-
.../metadata/GeoParquetMetadataDataSource.scala | 42 +-
.../GeoParquetMetadataPartitionReaderFactory.scala | 56 +-
.../metadata/GeoParquetMetadataScan.scala | 39 +-
.../metadata/GeoParquetMetadataScanBuilder.scala | 25 +-
.../metadata/GeoParquetMetadataTable.scala | 52 +-
.../sedona/sql/GeoParquetMetadataTests.scala | 77 +-
.../sql/GeoParquetSpatialFilterPushDownSuite.scala | 235 +-
.../org/apache/sedona/sql/TestBaseScala.scala | 10 +-
.../org/apache/sedona/sql/geoparquetIOTests.scala | 219 +-
.../maven/license-header.txt | 11 -
tools/maven/scalafmt.conf | 30 +
527 files changed, 74569 insertions(+), 61517 deletions(-)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 5e4504c03..d40341a5f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -17,14 +17,14 @@ repos:
name: Run codespell
description: Check spelling with codespell
args: [--ignore-words=.github/linters/codespell.txt]
- exclude: ^docs/image|^spark/common/src/test/resources|^docs/usecases
+ exclude: ^docs/image|^spark/common/src/test/resources|^docs/usecases|^tools/maven/scalafmt
- repo: https://github.com/astral-sh/ruff-pre-commit
- rev: v0.4.4
+ rev: v0.4.2
hooks:
- id: ruff
args: [--config=.github/linters/ruff.toml, --fix]
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.6.0
+ rev: v4.5.0
hooks:
- id: check-ast
- id: check-builtin-literals
@@ -57,7 +57,7 @@ repos:
args: [--markdown-linebreak-ext=md]
exclude: ^docs-overrides/main\.html$|\.Rd$
- repo: https://github.com/igorshubovych/markdownlint-cli
- rev: v0.40.0
+ rev: v0.38.0
hooks:
- id: markdownlint
name: Run markdownlint
diff --git a/LICENSE b/LICENSE
index 6dc8a4e52..18fb8842b 100644
--- a/LICENSE
+++ b/LICENSE
@@ -207,7 +207,8 @@ for text of these licenses.
Apache 2.0 License
--------------------------------------
-scalastyle_config.xml (copied from https://github.com/scalastyle/scalastyle/blob/master/lib/scalastyle_config.xml)
+tools/maven/scalastyle_config.xml (copied from https://github.com/scalastyle/scalastyle/blob/master/lib/scalastyle_config.xml)
+tools/maven/scalafmt.conf (copied from https://github.com/apache/spark/blob/master/dev/.scalafmt.conf)
BSD 2-Clause License
--------------------------------------
diff --git a/common/src/main/java/org/apache/sedona/common/Constructors.java b/common/src/main/java/org/apache/sedona/common/Constructors.java
index 31a339c38..572fba660 100644
--- a/common/src/main/java/org/apache/sedona/common/Constructors.java
+++ b/common/src/main/java/org/apache/sedona/common/Constructors.java
@@ -1,18 +1,25 @@
-/**
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sedona.common;
+import java.io.IOException;
+import javax.xml.parsers.ParserConfigurationException;
import org.apache.sedona.common.enums.FileDataSplitter;
import org.apache.sedona.common.enums.GeometryType;
import org.apache.sedona.common.utils.FormatUtils;
@@ -25,259 +32,254 @@ import org.locationtech.jts.io.gml2.GMLReader;
import org.locationtech.jts.io.kml.KMLReader;
import org.xml.sax.SAXException;
-import javax.xml.parsers.ParserConfigurationException;
-import java.io.IOException;
-
public class Constructors {
- private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
-
- public static Geometry geomFromWKT(String wkt, int srid) throws ParseException {
- if (wkt == null) {
- return null;
- }
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return new WKTReader(geometryFactory).read(wkt);
- }
-
- public static Geometry geomFromEWKT(String ewkt) throws ParseException {
- if (ewkt == null) {
- return null;
- }
- int SRID = 0;
- String wkt = ewkt;
-
- int index = ewkt.indexOf("SRID=");
- if (index != -1) {
- int semicolonIndex = ewkt.indexOf(';', index);
- if (semicolonIndex != -1) {
- SRID = Integer.parseInt(ewkt.substring(index + 5, semicolonIndex));
- wkt = ewkt.substring(semicolonIndex + 1);
- }
- else {
- throw new ParseException("Invalid EWKT string");
- }
- }
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), SRID);
- return new WKTReader(geometryFactory).read(wkt);
- }
-
- public static Geometry geomFromWKB(byte[] wkb) throws ParseException {
- return new WKBReader().read(wkb);
- }
-
- public static Geometry pointFromWKB(byte[] wkb) throws ParseException {
- return pointFromWKB(wkb, 0);
- }
-
- public static Geometry pointFromWKB(byte[] wkb, int srid) throws ParseException {
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- Geometry geom = new WKBReader(geometryFactory).read(wkb);
- if (!(geom instanceof Point)) {
- return null;
- }
- return geom;
- }
-
- public static Geometry lineFromWKB(byte[] wkb) throws ParseException {
- return lineFromWKB(wkb, 0);
- }
-
- public static Geometry lineFromWKB(byte[] wkb, int srid) throws ParseException {
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- Geometry geom = new WKBReader(geometryFactory).read(wkb);
- if (!(geom instanceof LineString)) {
- return null;
- }
- return geom;
- }
-
- public static Geometry mPointFromText(String wkt, int srid) throws ParseException {
- if (wkt == null || !wkt.startsWith("MULTIPOINT")) {
- return null;
- }
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return new WKTReader(geometryFactory).read(wkt);
- }
+ private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
- public static Geometry mLineFromText(String wkt, int srid) throws ParseException {
- if (wkt == null || !wkt.startsWith("MULTILINESTRING")) {
- return null;
- }
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return new WKTReader(geometryFactory).read(wkt);
+ public static Geometry geomFromWKT(String wkt, int srid) throws ParseException {
+ if (wkt == null) {
+ return null;
}
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return new WKTReader(geometryFactory).read(wkt);
+ }
- public static Geometry mPolyFromText(String wkt, int srid) throws ParseException {
- if (wkt == null || !wkt.startsWith("MULTIPOLYGON")) {
- return null;
- }
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return new WKTReader(geometryFactory).read(wkt);
+ public static Geometry geomFromEWKT(String ewkt) throws ParseException {
+ if (ewkt == null) {
+ return null;
}
-
- public static Geometry geomCollFromText(String wkt, int srid) throws ParseException {
- if (wkt == null || !wkt.startsWith("GEOMETRYCOLLECTION")) {
- return null;
- }
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return new WKTReader(geometryFactory).read(wkt);
+ int SRID = 0;
+ String wkt = ewkt;
+
+ int index = ewkt.indexOf("SRID=");
+ if (index != -1) {
+ int semicolonIndex = ewkt.indexOf(';', index);
+ if (semicolonIndex != -1) {
+ SRID = Integer.parseInt(ewkt.substring(index + 5, semicolonIndex));
+ wkt = ewkt.substring(semicolonIndex + 1);
+ } else {
+ throw new ParseException("Invalid EWKT string");
+ }
}
-
-
- /**
- * Creates a point from the given coordinate.
- * ST_Point in Sedona Spark API took an optional z value before v1.4.0.
- * This was removed to avoid confusion with other GIS implementations where the optional third argument is srid.
- *
- * A future version of Sedona will add a srid parameter once enough users have upgraded and hence are forced
- * to use ST_PointZ for 3D points.
- *
- * @param x the x value
- * @param y the y value
- * @return The point geometry
- */
- public static Geometry point(double x, double y) {
- // See srid parameter discussion in https://issues.apache.org/jira/browse/SEDONA-234
- GeometryFactory geometryFactory = new GeometryFactory();
- return geometryFactory.createPoint(new Coordinate(x, y));
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), SRID);
+ return new WKTReader(geometryFactory).read(wkt);
+ }
+
+ public static Geometry geomFromWKB(byte[] wkb) throws ParseException {
+ return new WKBReader().read(wkb);
+ }
+
+ public static Geometry pointFromWKB(byte[] wkb) throws ParseException {
+ return pointFromWKB(wkb, 0);
+ }
+
+ public static Geometry pointFromWKB(byte[] wkb, int srid) throws ParseException {
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ Geometry geom = new WKBReader(geometryFactory).read(wkb);
+ if (!(geom instanceof Point)) {
+ return null;
}
-
- public static Geometry makePointM(double x, double y, double m) {
- GeometryFactory geometryFactory = new GeometryFactory();
- return geometryFactory.createPoint(new CoordinateXYM(x, y, m));
+ return geom;
+ }
+
+ public static Geometry lineFromWKB(byte[] wkb) throws ParseException {
+ return lineFromWKB(wkb, 0);
+ }
+
+ public static Geometry lineFromWKB(byte[] wkb, int srid) throws ParseException {
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ Geometry geom = new WKBReader(geometryFactory).read(wkb);
+ if (!(geom instanceof LineString)) {
+ return null;
}
+ return geom;
+ }
- public static Geometry makePoint(Double x, Double y, Double z, Double m){
- GeometryFactory geometryFactory = new GeometryFactory();
- if (x == null || y == null) {
- return null;
- }
- if (z == null && m == null) {
- return geometryFactory.createPoint(new Coordinate(x, y));
- }
- if (z != null && m == null) {
- return geometryFactory.createPoint(new Coordinate(x, y, z));
- }
- if (z == null) {
- return geometryFactory.createPoint(new CoordinateXYZM(x, y, 0, m));
- }
- return geometryFactory.createPoint(new CoordinateXYZM(x, y, z, m));
+ public static Geometry mPointFromText(String wkt, int srid) throws ParseException {
+ if (wkt == null || !wkt.startsWith("MULTIPOINT")) {
+ return null;
}
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return new WKTReader(geometryFactory).read(wkt);
+ }
- /**
- * Creates a point from the given coordinate.
- *
- * @param x the x value
- * @param y the y value
- * @param z the z value
- * @param srid Set to 0 if unknown
- * @return The point geometry
- */
- public static Geometry pointZ(double x, double y, double z, int srid) {
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return geometryFactory.createPoint(new Coordinate(x, y, z));
+ public static Geometry mLineFromText(String wkt, int srid) throws ParseException {
+ if (wkt == null || !wkt.startsWith("MULTILINESTRING")) {
+ return null;
}
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return new WKTReader(geometryFactory).read(wkt);
+ }
- /**
- * Creates a point from the given coordinate.
- *
- * @param x the x value
- * @param y the y value
- * @param m the m value
- * @param srid Set to 0 if unknown
- * @return The point geometry
- */
- public static Geometry pointM(double x, double y, double m, int srid) {
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return geometryFactory.createPoint(new CoordinateXYZM(x, y, 0, m));
+ public static Geometry mPolyFromText(String wkt, int srid) throws ParseException {
+ if (wkt == null || !wkt.startsWith("MULTIPOLYGON")) {
+ return null;
}
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return new WKTReader(geometryFactory).read(wkt);
+ }
- /**
- * Creates a point from the given coordinate.
- *
- * @param x the x value
- * @param y the y value
- * @param z the z value
- * @param m the m value
- * @param srid Set to 0 if unknown
- * @return The point geometry
- */
- public static Geometry pointZM(double x, double y, double z, double m, int srid) {
- GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
- return geometryFactory.createPoint(new CoordinateXYZM(x, y, z, m));
+ public static Geometry geomCollFromText(String wkt, int srid) throws ParseException {
+ if (wkt == null || !wkt.startsWith("GEOMETRYCOLLECTION")) {
+ return null;
}
-
- public static Geometry geomFromText(String geomString, String geomFormat, GeometryType geometryType) {
- FileDataSplitter fileDataSplitter = FileDataSplitter.getFileDataSplitter(geomFormat);
- FormatUtils<Geometry> formatMapper = new FormatUtils<>(fileDataSplitter, false, geometryType);
- try {
- return formatMapper.readGeometry(geomString);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return new WKTReader(geometryFactory).read(wkt);
+ }
+
+ /**
+ * Creates a point from the given coordinate. ST_Point in Sedona Spark API took an optional z
+ * value before v1.4.0. This was removed to avoid confusion with other GIS implementations where
+ * the optional third argument is srid.
+ *
+ * <p>A future version of Sedona will add a srid parameter once enough users have upgraded and
+ * hence are forced to use ST_PointZ for 3D points.
+ *
+ * @param x the x value
+ * @param y the y value
+ * @return The point geometry
+ */
+ public static Geometry point(double x, double y) {
+ // See srid parameter discussion in https://issues.apache.org/jira/browse/SEDONA-234
+ GeometryFactory geometryFactory = new GeometryFactory();
+ return geometryFactory.createPoint(new Coordinate(x, y));
+ }
+
+ public static Geometry makePointM(double x, double y, double m) {
+ GeometryFactory geometryFactory = new GeometryFactory();
+ return geometryFactory.createPoint(new CoordinateXYM(x, y, m));
+ }
+
+ public static Geometry makePoint(Double x, Double y, Double z, Double m) {
+ GeometryFactory geometryFactory = new GeometryFactory();
+ if (x == null || y == null) {
+ return null;
}
-
- public static Geometry geomFromText(String geomString, FileDataSplitter fileDataSplitter) {
- FormatUtils<Geometry> formatMapper = new FormatUtils<>(fileDataSplitter, false);
- try {
- return formatMapper.readGeometry(geomString);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
+ if (z == null && m == null) {
+ return geometryFactory.createPoint(new Coordinate(x, y));
}
-
- public static Geometry pointFromText(String geomString, String geomFormat) {
- return geomFromText(geomString, geomFormat, GeometryType.POINT);
+ if (z != null && m == null) {
+ return geometryFactory.createPoint(new Coordinate(x, y, z));
}
-
- public static Geometry polygonFromText(String geomString, String geomFormat) {
- return geomFromText(geomString, geomFormat, GeometryType.POLYGON);
+ if (z == null) {
+ return geometryFactory.createPoint(new CoordinateXYZM(x, y, 0, m));
}
-
- public static Geometry lineStringFromText(String geomString, String geomFormat) {
- return geomFromText(geomString, geomFormat, GeometryType.LINESTRING);
+ return geometryFactory.createPoint(new CoordinateXYZM(x, y, z, m));
+ }
+
+ /**
+ * Creates a point from the given coordinate.
+ *
+ * @param x the x value
+ * @param y the y value
+ * @param z the z value
+ * @param srid Set to 0 if unknown
+ * @return The point geometry
+ */
+ public static Geometry pointZ(double x, double y, double z, int srid) {
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return geometryFactory.createPoint(new Coordinate(x, y, z));
+ }
+
+ /**
+ * Creates a point from the given coordinate.
+ *
+ * @param x the x value
+ * @param y the y value
+ * @param m the m value
+ * @param srid Set to 0 if unknown
+ * @return The point geometry
+ */
+ public static Geometry pointM(double x, double y, double m, int srid) {
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return geometryFactory.createPoint(new CoordinateXYZM(x, y, 0, m));
+ }
+
+ /**
+ * Creates a point from the given coordinate.
+ *
+ * @param x the x value
+ * @param y the y value
+ * @param z the z value
+ * @param m the m value
+ * @param srid Set to 0 if unknown
+ * @return The point geometry
+ */
+ public static Geometry pointZM(double x, double y, double z, double m, int srid) {
+ GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
+ return geometryFactory.createPoint(new CoordinateXYZM(x, y, z, m));
+ }
+
+ public static Geometry geomFromText(
+ String geomString, String geomFormat, GeometryType geometryType) {
+ FileDataSplitter fileDataSplitter = FileDataSplitter.getFileDataSplitter(geomFormat);
+ FormatUtils<Geometry> formatMapper = new FormatUtils<>(fileDataSplitter, false, geometryType);
+ try {
+ return formatMapper.readGeometry(geomString);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
}
-
- public static Geometry lineFromText(String geomString) {
- FileDataSplitter fileDataSplitter = FileDataSplitter.WKT;
- Geometry geometry = Constructors.geomFromText(geomString, fileDataSplitter);
- if(geometry.getGeometryType().contains("LineString")) {
- return geometry;
- } else {
- return null;
- }
+ }
+
+ public static Geometry geomFromText(String geomString, FileDataSplitter fileDataSplitter) {
+ FormatUtils<Geometry> formatMapper = new FormatUtils<>(fileDataSplitter, false);
+ try {
+ return formatMapper.readGeometry(geomString);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
}
-
- public static Geometry polygonFromEnvelope(double minX, double minY, double maxX, double maxY) {
- Coordinate[] coordinates = new Coordinate[5];
- coordinates[0] = new Coordinate(minX, minY);
- coordinates[1] = new Coordinate(minX, maxY);
- coordinates[2] = new Coordinate(maxX, maxY);
- coordinates[3] = new Coordinate(maxX, minY);
- coordinates[4] = coordinates[0];
- return GEOMETRY_FACTORY.createPolygon(coordinates);
+ }
+
+ public static Geometry pointFromText(String geomString, String geomFormat) {
+ return geomFromText(geomString, geomFormat, GeometryType.POINT);
+ }
+
+ public static Geometry polygonFromText(String geomString, String geomFormat) {
+ return geomFromText(geomString, geomFormat, GeometryType.POLYGON);
+ }
+
+ public static Geometry lineStringFromText(String geomString, String geomFormat) {
+ return geomFromText(geomString, geomFormat, GeometryType.LINESTRING);
+ }
+
+ public static Geometry lineFromText(String geomString) {
+ FileDataSplitter fileDataSplitter = FileDataSplitter.WKT;
+ Geometry geometry = Constructors.geomFromText(geomString, fileDataSplitter);
+ if (geometry.getGeometryType().contains("LineString")) {
+ return geometry;
+ } else {
+ return null;
}
-
- public static Geometry geomFromGeoHash(String geoHash, Integer precision) {
- try {
- return GeoHashDecoder.decode(geoHash, precision);
- } catch (GeoHashDecoder.InvalidGeoHashException e) {
- return null;
- }
+ }
+
+ public static Geometry polygonFromEnvelope(double minX, double minY, double maxX, double maxY) {
+ Coordinate[] coordinates = new Coordinate[5];
+ coordinates[0] = new Coordinate(minX, minY);
+ coordinates[1] = new Coordinate(minX, maxY);
+ coordinates[2] = new Coordinate(maxX, maxY);
+ coordinates[3] = new Coordinate(maxX, minY);
+ coordinates[4] = coordinates[0];
+ return GEOMETRY_FACTORY.createPolygon(coordinates);
+ }
+
+ public static Geometry geomFromGeoHash(String geoHash, Integer precision) {
+ try {
+ return GeoHashDecoder.decode(geoHash, precision);
+ } catch (GeoHashDecoder.InvalidGeoHashException e) {
+ return null;
}
+ }
- public static Geometry pointFromGeoHash(String geoHash, Integer precision) {
- return geomFromGeoHash(geoHash, precision).getCentroid();
- }
-
- public static Geometry geomFromGML(String gml) throws IOException, ParserConfigurationException, SAXException {
- return new GMLReader().read(gml, GEOMETRY_FACTORY);
- }
-
- public static Geometry geomFromKML(String kml) throws ParseException {
- return new KMLReader().read(kml);
- }
+ public static Geometry pointFromGeoHash(String geoHash, Integer precision) {
+ return geomFromGeoHash(geoHash, precision).getCentroid();
+ }
+ public static Geometry geomFromGML(String gml)
+ throws IOException, ParserConfigurationException, SAXException {
+ return new GMLReader().read(gml, GEOMETRY_FACTORY);
+ }
+ public static Geometry geomFromKML(String kml) throws ParseException {
+ return new KMLReader().read(kml);
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/Functions.java b/common/src/main/java/org/apache/sedona/common/Functions.java
index e85e8d330..18a8403bf 100644
--- a/common/src/main/java/org/apache/sedona/common/Functions.java
+++ b/common/src/main/java/org/apache/sedona/common/Functions.java
@@ -1,22 +1,31 @@
-/**
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sedona.common;
+import static com.google.common.geometry.S2.DBL_EPSILON;
+import static org.apache.sedona.common.FunctionsGeoTools.bufferSpheroid;
+
import com.google.common.geometry.S2CellId;
import com.uber.h3core.exceptions.H3Exception;
-
import com.uber.h3core.util.LatLng;
+import java.util.*;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.sedona.common.geometryObjects.Circle;
import org.apache.sedona.common.sphere.Spheroid;
@@ -52,1870 +61,1987 @@ import org.locationtech.jts.triangulate.DelaunayTriangulationBuilder;
import org.locationtech.jts.triangulate.polygon.ConstrainedDelaunayTriangulator;
import org.wololo.jts2geojson.GeoJSONWriter;
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static com.google.common.geometry.S2.DBL_EPSILON;
-import static org.apache.sedona.common.FunctionsGeoTools.bufferSpheroid;
-
-
public class Functions {
- private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
- private static Geometry EMPTY_POLYGON = GEOMETRY_FACTORY.createPolygon(null, null);
- private static GeometryCollection EMPTY_GEOMETRY_COLLECTION = GEOMETRY_FACTORY.createGeometryCollection(null);
- private static final double DEFAULT_TOLERANCE = 1e-6;
- private static final int DEFAULT_MAX_ITER = 1000;
- private static final int OGC_SFS_VALIDITY = 0; // Use usual OGC SFS validity semantics
- private static final int ESRI_VALIDITY = 1; // ESRI validity model
-
- public static double area(Geometry geometry) {
- return geometry.getArea();
- }
-
- public static double azimuth(Geometry left, Geometry right) {
- Coordinate leftCoordinate = left.getCoordinate();
- Coordinate rightCoordinate = right.getCoordinate();
- double deltaX = rightCoordinate.x - leftCoordinate.x;
- double deltaY = rightCoordinate.y - leftCoordinate.y;
- double azimuth = Math.atan2(deltaX, deltaY);
- return azimuth < 0 ? azimuth + (2 * Math.PI) : azimuth;
- }
-
- public static Geometry boundary(Geometry geometry) {
- Geometry boundary = geometry.getBoundary();
- if (boundary instanceof LinearRing) {
- boundary = GEOMETRY_FACTORY.createLineString(boundary.getCoordinates());
- }
- return boundary;
- }
-
- public static Geometry buffer(Geometry geometry, double radius) {
- return buffer(geometry, radius, false, "");
- }
-
- public static Geometry buffer(Geometry geometry, double radius, boolean useSpheroid) {
- return buffer(geometry, radius, useSpheroid, "");
- }
-
- public static Geometry buffer(Geometry geometry, double radius, boolean useSpheroid, String params) throws IllegalArgumentException {
- BufferParameters bufferParameters = new BufferParameters();
-
- // Processing parameters
- if (!params.isEmpty()) {
- bufferParameters = parseBufferParams(params);
-
- // convert the sign to the appropriate direction
- // left - radius should be positive
- // right - radius should be negative
- if (bufferParameters.isSingleSided() &&
- (params.toLowerCase().contains("left") && radius < 0 || params.toLowerCase().contains("right") && radius > 0)) {
- radius = -radius;
- }
- }
-
- if (useSpheroid) {
- // Spheroidal buffering logic
- try {
- return bufferSpheroid(geometry, radius, bufferParameters);
- } catch (RuntimeException e) {
- throw new RuntimeException("Error processing spheroidal buffer", e);
- }
+ private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
+ private static Geometry EMPTY_POLYGON = GEOMETRY_FACTORY.createPolygon(null, null);
+ private static GeometryCollection EMPTY_GEOMETRY_COLLECTION =
+ GEOMETRY_FACTORY.createGeometryCollection(null);
+ private static final double DEFAULT_TOLERANCE = 1e-6;
+ private static final int DEFAULT_MAX_ITER = 1000;
+ private static final int OGC_SFS_VALIDITY = 0; // Use usual OGC SFS validity semantics
+ private static final int ESRI_VALIDITY = 1; // ESRI validity model
+
+ public static double area(Geometry geometry) {
+ return geometry.getArea();
+ }
+
+ public static double azimuth(Geometry left, Geometry right) {
+ Coordinate leftCoordinate = left.getCoordinate();
+ Coordinate rightCoordinate = right.getCoordinate();
+ double deltaX = rightCoordinate.x - leftCoordinate.x;
+ double deltaY = rightCoordinate.y - leftCoordinate.y;
+ double azimuth = Math.atan2(deltaX, deltaY);
+ return azimuth < 0 ? azimuth + (2 * Math.PI) : azimuth;
+ }
+
+ public static Geometry boundary(Geometry geometry) {
+ Geometry boundary = geometry.getBoundary();
+ if (boundary instanceof LinearRing) {
+ boundary = GEOMETRY_FACTORY.createLineString(boundary.getCoordinates());
+ }
+ return boundary;
+ }
+
+ public static Geometry buffer(Geometry geometry, double radius) {
+ return buffer(geometry, radius, false, "");
+ }
+
+ public static Geometry buffer(Geometry geometry, double radius, boolean useSpheroid) {
+ return buffer(geometry, radius, useSpheroid, "");
+ }
+
+ public static Geometry buffer(
+ Geometry geometry, double radius, boolean useSpheroid, String params)
+ throws IllegalArgumentException {
+ BufferParameters bufferParameters = new BufferParameters();
+
+ // Processing parameters
+ if (!params.isEmpty()) {
+ bufferParameters = parseBufferParams(params);
+
+ // convert the sign to the appropriate direction
+ // left - radius should be positive
+ // right - radius should be negative
+ if (bufferParameters.isSingleSided()
+ && (params.toLowerCase().contains("left") && radius < 0
+ || params.toLowerCase().contains("right") && radius > 0)) {
+ radius = -radius;
+ }
+ }
+
+ if (useSpheroid) {
+ // Spheroidal buffering logic
+ try {
+ return bufferSpheroid(geometry, radius, bufferParameters);
+ } catch (RuntimeException e) {
+ throw new RuntimeException("Error processing spheroidal buffer", e);
+ }
+ } else {
+ // Existing planar buffer logic with params handling
+ return BufferOp.bufferOp(geometry, radius, bufferParameters);
+ }
+ }
+
+ private static BufferParameters parseBufferParams(String params) {
+
+ String[] listBufferParameters = {
+ "quad_segs", "endcap", "join", "mitre_limit", "miter_limit", "side"
+ };
+ String[] endcapOptions = {"round", "flat", "butt", "square"};
+ String[] joinOptions = {"round", "mitre", "miter", "bevel"};
+ String[] sideOptions = {"both", "left", "right"};
+
+ BufferParameters bufferParameters = new BufferParameters();
+ String[] listParams = params.split(" ");
+
+ for (String param : listParams) {
+ String[] singleParam = param.split("=");
+
+ if (singleParam.length != 2) {
+ throw new IllegalArgumentException(
+ String.format(
+ "%s is not the valid format. The valid format is key=value, for example `endcap=butt quad_segs=4`.",
+ param));
+ }
+
+ // Set quadrant segment
+ if (singleParam[0].equalsIgnoreCase(listBufferParameters[0])) {
+ try {
+ bufferParameters.setQuadrantSegments(Integer.parseInt(singleParam[1]));
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ String.format(
+ "%1$s is not an integer. Quadrant segment should be an integer.",
+ singleParam[1]));
+ }
+ }
+ // Set end cap style
+ else if (singleParam[0].equalsIgnoreCase(listBufferParameters[1])) {
+ if (singleParam[1].equalsIgnoreCase(endcapOptions[0])) {
+ bufferParameters.setEndCapStyle(BufferParameters.CAP_ROUND);
+ } else if (singleParam[1].equalsIgnoreCase(endcapOptions[1])
+ || singleParam[1].equalsIgnoreCase(endcapOptions[2])) {
+ bufferParameters.setEndCapStyle(BufferParameters.CAP_FLAT);
+ } else if (singleParam[1].equalsIgnoreCase(endcapOptions[3])) {
+ bufferParameters.setEndCapStyle(BufferParameters.CAP_SQUARE);
} else {
- // Existing planar buffer logic with params handling
- return BufferOp.bufferOp(geometry, radius, bufferParameters);
- }
- }
-
- private static BufferParameters parseBufferParams(String params) {
-
- String[] listBufferParameters = {"quad_segs", "endcap", "join", "mitre_limit", "miter_limit", "side"};
- String[] endcapOptions = {"round", "flat", "butt", "square"};
- String[] joinOptions = {"round", "mitre", "miter", "bevel"};
- String[] sideOptions = {"both", "left", "right"};
-
- BufferParameters bufferParameters = new BufferParameters();
- String[] listParams = params.split(" ");
-
- for (String param: listParams) {
- String[] singleParam = param.split("=");
-
- if (singleParam.length != 2) {
- throw new IllegalArgumentException(String.format("%s is not the valid format. The valid format is key=value, for example `endcap=butt quad_segs=4`.", param));
- }
-
- // Set quadrant segment
- if (singleParam[0].equalsIgnoreCase(listBufferParameters[0])) {
- try {
- bufferParameters.setQuadrantSegments(Integer.parseInt(singleParam[1]));
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException(String.format("%1$s is not an integer. Quadrant segment should be an integer.", singleParam[1]));
- }
- }
- // Set end cap style
- else if (singleParam[0].equalsIgnoreCase(listBufferParameters[1])) {
- if (singleParam[1].equalsIgnoreCase(endcapOptions[0])) {
- bufferParameters.setEndCapStyle(BufferParameters.CAP_ROUND);
- } else if (singleParam[1].equalsIgnoreCase(endcapOptions[1]) || singleParam[1].equalsIgnoreCase(endcapOptions[2])) {
- bufferParameters.setEndCapStyle(BufferParameters.CAP_FLAT);
- } else if (singleParam[1].equalsIgnoreCase(endcapOptions[3])) {
- bufferParameters.setEndCapStyle(BufferParameters.CAP_SQUARE);
- } else {
- throw new IllegalArgumentException(String.format("%s is not a valid option. Accepted options are %s.", singleParam[1], Arrays.toString(endcapOptions)));
- }
- }
- // Set join style
- else if (singleParam[0].equalsIgnoreCase(listBufferParameters[2])) {
- if (singleParam[1].equalsIgnoreCase(joinOptions[0])) {
- bufferParameters.setJoinStyle(BufferParameters.JOIN_ROUND);
- } else if (singleParam[1].equalsIgnoreCase(joinOptions[1]) || singleParam[1].equalsIgnoreCase(joinOptions[2])) {
- bufferParameters.setJoinStyle(BufferParameters.JOIN_MITRE);
- } else if (singleParam[1].equalsIgnoreCase(joinOptions[3])) {
- bufferParameters.setJoinStyle(BufferParameters.JOIN_BEVEL);
- } else {
- throw new IllegalArgumentException(String.format("%s is not a valid option. Accepted options are %s", singleParam[1], Arrays.toString(joinOptions)));
- }
- }
- // Set mitre ratio limit
- else if (singleParam[0].equalsIgnoreCase(listBufferParameters[3]) || singleParam[0].equalsIgnoreCase(listBufferParameters[4])) {
- try {
- bufferParameters.setMitreLimit(Double.parseDouble(singleParam[1]));
- } catch (NumberFormatException e) {
- throw new IllegalArgumentException(String.format("%1$s is not a double. Mitre limit should be a double.", singleParam[1]));
- }
- continue;
- }
- // Set side to add buffer
- else if (singleParam[0].equalsIgnoreCase(listBufferParameters[5])) {
- if (singleParam[1].equalsIgnoreCase(sideOptions[0])) {
- // It defaults to square end cap style when side is specified
- bufferParameters.setEndCapStyle(BufferParameters.CAP_SQUARE);
- continue;
- } else if (singleParam[1].equalsIgnoreCase(sideOptions[1]) || singleParam[1].equalsIgnoreCase(sideOptions[2])) {
- bufferParameters.setSingleSided(true);
- } else {
- throw new IllegalArgumentException(String.format("%s is not a valid option. Accepted options are %s ", singleParam[1], Arrays.toString(sideOptions)));
- }
- }
- // everything else
- else {
- throw new IllegalArgumentException(String.format("%s is not a valid style parameter. Accepted style parameters are %s.", singleParam[0], Arrays.toString(listBufferParameters)));
- }
- }
- return bufferParameters;
- }
-
- public static int bestSRID(Geometry geometry) throws IllegalArgumentException {
- // Shift longitudes if geometry crosses dateline
- if (crossesDateLine(geometry)) {
- shiftLongitude(geometry);
- }
-
- // Check envelope
- Envelope envelope = geometry.getEnvelopeInternal();
- if (envelope.isNull()) return Spheroid.EPSG_WORLD_MERCATOR; // Fallback EPSG
-
- // Calculate the center of the envelope
- double centerX = (envelope.getMinX() + envelope.getMaxX()) / 2.0; // centroid.getX();
- double centerY = (envelope.getMinY() + envelope.getMaxY()) / 2.0; // centroid.getY();
-
- // Calculate angular width and height
- Double xwidth = Spheroid.angularWidth(envelope);
- Double ywidth = Spheroid.angularHeight(envelope);
- if (xwidth.isNaN() | ywidth.isNaN()) {
- throw new IllegalArgumentException("Only lon/lat coordinate systems are supported by ST_BestSRID");
- }
-
- // Prioritize polar regions for Lambert Azimuthal Equal Area projection
- if (centerY >= 70.0 && ywidth < 45.0) return Spheroid.EPSG_NORTH_LAMBERT;
- if (centerY <= -70.0 && ywidth < 45.0) return Spheroid.EPSG_SOUTH_LAMBERT;
-
- // Check for UTM zones
- if (xwidth < 6.0) {
- int zone;
- if (centerX == -180.0 || centerX == 180.0) {
- zone = 59; // UTM zone 60
- } else {
- zone = (int) Math.floor((centerX + 180.0) / 6.0);
- zone = (zone > 59) ? zone - 60 : zone;
- }
- return (centerY < 0.0) ? Spheroid.EPSG_SOUTH_UTM_START + zone : Spheroid.EPSG_NORTH_UTM_START + zone;
- }
-
- // Default fallback to Mercator projection
- return Spheroid.EPSG_WORLD_MERCATOR;
- }
-
- /**
- * Corrects the longitudes of a geometry to be within the -180 to 180 range.
- * This method modifies the original geometry.
- *
- * @param geometry The geometry to be corrected.
- */
- public static void normalizeLongitude(Geometry geometry) {
- if (geometry == null || geometry.isEmpty()) {
- return;
- }
+ throw new IllegalArgumentException(
+ String.format(
+ "%s is not a valid option. Accepted options are %s.",
+ singleParam[1], Arrays.toString(endcapOptions)));
+ }
+ }
+ // Set join style
+ else if (singleParam[0].equalsIgnoreCase(listBufferParameters[2])) {
+ if (singleParam[1].equalsIgnoreCase(joinOptions[0])) {
+ bufferParameters.setJoinStyle(BufferParameters.JOIN_ROUND);
+ } else if (singleParam[1].equalsIgnoreCase(joinOptions[1])
+ || singleParam[1].equalsIgnoreCase(joinOptions[2])) {
+ bufferParameters.setJoinStyle(BufferParameters.JOIN_MITRE);
+ } else if (singleParam[1].equalsIgnoreCase(joinOptions[3])) {
+ bufferParameters.setJoinStyle(BufferParameters.JOIN_BEVEL);
+ } else {
+ throw new IllegalArgumentException(
+ String.format(
+ "%s is not a valid option. Accepted options are %s",
+ singleParam[1], Arrays.toString(joinOptions)));
+ }
+ }
+ // Set mitre ratio limit
+ else if (singleParam[0].equalsIgnoreCase(listBufferParameters[3])
+ || singleParam[0].equalsIgnoreCase(listBufferParameters[4])) {
+ try {
+ bufferParameters.setMitreLimit(Double.parseDouble(singleParam[1]));
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ String.format(
+ "%1$s is not a double. Mitre limit should be a double.", singleParam[1]));
+ }
+ continue;
+ }
+ // Set side to add buffer
+ else if (singleParam[0].equalsIgnoreCase(listBufferParameters[5])) {
+ if (singleParam[1].equalsIgnoreCase(sideOptions[0])) {
+ // It defaults to square end cap style when side is specified
+ bufferParameters.setEndCapStyle(BufferParameters.CAP_SQUARE);
+ continue;
+ } else if (singleParam[1].equalsIgnoreCase(sideOptions[1])
+ || singleParam[1].equalsIgnoreCase(sideOptions[2])) {
+ bufferParameters.setSingleSided(true);
+ } else {
+ throw new IllegalArgumentException(
+ String.format(
+ "%s is not a valid option. Accepted options are %s ",
+ singleParam[1], Arrays.toString(sideOptions)));
+ }
+ }
+ // everything else
+ else {
+ throw new IllegalArgumentException(
+ String.format(
+ "%s is not a valid style parameter. Accepted style parameters are %s.",
+ singleParam[0], Arrays.toString(listBufferParameters)));
+ }
+ }
+ return bufferParameters;
+ }
+
+ public static int bestSRID(Geometry geometry) throws IllegalArgumentException {
+ // Shift longitudes if geometry crosses dateline
+ if (crossesDateLine(geometry)) {
+ shiftLongitude(geometry);
+ }
+
+ // Check envelope
+ Envelope envelope = geometry.getEnvelopeInternal();
+ if (envelope.isNull()) return Spheroid.EPSG_WORLD_MERCATOR; // Fallback EPSG
+
+ // Calculate the center of the envelope
+ double centerX = (envelope.getMinX() + envelope.getMaxX()) / 2.0; // centroid.getX();
+ double centerY = (envelope.getMinY() + envelope.getMaxY()) / 2.0; // centroid.getY();
+
+ // Calculate angular width and height
+ Double xwidth = Spheroid.angularWidth(envelope);
+ Double ywidth = Spheroid.angularHeight(envelope);
+ if (xwidth.isNaN() | ywidth.isNaN()) {
+ throw new IllegalArgumentException(
+ "Only lon/lat coordinate systems are supported by ST_BestSRID");
+ }
+
+ // Prioritize polar regions for Lambert Azimuthal Equal Area projection
+ if (centerY >= 70.0 && ywidth < 45.0) return Spheroid.EPSG_NORTH_LAMBERT;
+ if (centerY <= -70.0 && ywidth < 45.0) return Spheroid.EPSG_SOUTH_LAMBERT;
+
+ // Check for UTM zones
+ if (xwidth < 6.0) {
+ int zone;
+ if (centerX == -180.0 || centerX == 180.0) {
+ zone = 59; // UTM zone 60
+ } else {
+ zone = (int) Math.floor((centerX + 180.0) / 6.0);
+ zone = (zone > 59) ? zone - 60 : zone;
+ }
+ return (centerY < 0.0)
+ ? Spheroid.EPSG_SOUTH_UTM_START + zone
+ : Spheroid.EPSG_NORTH_UTM_START + zone;
+ }
+
+ // Default fallback to Mercator projection
+ return Spheroid.EPSG_WORLD_MERCATOR;
+ }
+
+ /**
+ * Corrects the longitudes of a geometry to be within the -180 to 180 range. This method modifies
+ * the original geometry.
+ *
+ * @param geometry The geometry to be corrected.
+ */
+ public static void normalizeLongitude(Geometry geometry) {
+ if (geometry == null || geometry.isEmpty()) {
+ return;
+ }
+
+ geometry.apply(
+ new CoordinateSequenceFilter() {
+ @Override
+ public void filter(CoordinateSequence seq, int i) {
+ double x = seq.getX(i);
+ // Normalize the longitude to be within -180 to 180 range
+ while (x > 180) x -= 360;
+ while (x < -180) x += 360;
+ seq.setOrdinate(i, CoordinateSequence.X, x);
+ }
+
+ @Override
+ public boolean isDone() {
+ return false; // Continue processing until all coordinates are processed
+ }
+
+ @Override
+ public boolean isGeometryChanged() {
+ return true; // The geometry is changed as we are modifying the coordinates
+ }
+ });
- geometry.apply(new CoordinateSequenceFilter() {
- @Override
- public void filter(CoordinateSequence seq, int i) {
- double x = seq.getX(i);
- // Normalize the longitude to be within -180 to 180 range
- while (x > 180) x -= 360;
- while (x < -180) x += 360;
- seq.setOrdinate(i, CoordinateSequence.X, x);
+ geometry.geometryChanged(); // Notify the geometry that its coordinates have been changed
+ }
+
+ /**
+ * Checks if a geometry crosses the International Date Line.
+ *
+ * @param geometry The geometry to check.
+ * @return True if the geometry crosses the Date Line, false otherwise.
+ */
+ public static boolean crossesDateLine(Geometry geometry) {
+ if (geometry == null || geometry.isEmpty()) {
+ return false;
+ }
+
+ CoordinateSequenceFilter filter =
+ new CoordinateSequenceFilter() {
+ private Coordinate previous = null;
+ private boolean crossesDateLine = false;
+
+ @Override
+ public void filter(CoordinateSequence seq, int i) {
+ if (i == 0) {
+ previous = seq.getCoordinateCopy(i);
+ return;
}
- @Override
- public boolean isDone() {
- return false; // Continue processing until all coordinates are processed
+ Coordinate current = seq.getCoordinateCopy(i);
+ if (Math.abs(current.x - previous.x) > 180) {
+ crossesDateLine = true;
}
- @Override
- public boolean isGeometryChanged() {
- return true; // The geometry is changed as we are modifying the coordinates
- }
- });
+ previous = current;
+ }
- geometry.geometryChanged(); // Notify the geometry that its coordinates have been changed
- }
+ @Override
+ public boolean isDone() {
+ return crossesDateLine;
+ }
- /**
- * Checks if a geometry crosses the International Date Line.
- *
- * @param geometry The geometry to check.
- * @return True if the geometry crosses the Date Line, false otherwise.
- */
- public static boolean crossesDateLine(Geometry geometry) {
- if (geometry == null || geometry.isEmpty()) {
+ @Override
+ public boolean isGeometryChanged() {
return false;
- }
-
- CoordinateSequenceFilter filter = new CoordinateSequenceFilter() {
- private Coordinate previous = null;
- private boolean crossesDateLine = false;
-
- @Override
- public void filter(CoordinateSequence seq, int i) {
- if (i == 0) {
- previous = seq.getCoordinateCopy(i);
- return;
- }
-
- Coordinate current = seq.getCoordinateCopy(i);
- if (Math.abs(current.x - previous.x) > 180) {
- crossesDateLine = true;
- }
-
- previous = current;
- }
-
- @Override
- public boolean isDone() {
- return crossesDateLine;
- }
-
- @Override
- public boolean isGeometryChanged() {
- return false;
- }
+ }
};
- geometry.apply(filter);
- return filter.isDone();
- }
-
- public static Geometry shiftLongitude (Geometry geometry){
- geometry.apply(new CoordinateSequenceFilter() {
- @Override
- public void filter(CoordinateSequence seq, int i) {
- double newX = seq.getX(i);
- if (newX < 0) {
- newX += 360;
- } else if (newX > 180) {
- newX -= 360;
- }
- seq.setOrdinate(i, CoordinateSequence.X, newX);
- }
-
- @Override
- public boolean isDone() {
- return false;
- }
-
- @Override
- public boolean isGeometryChanged() {
- return true;
- }
- });
- return geometry;
- }
-
- public static Geometry envelope (Geometry geometry){
- return geometry.getEnvelope();
- }
-
- public static double distance (Geometry left, Geometry right){
- return left.distance(right);
- }
-
- public static double distance3d (Geometry left, Geometry right){
- return new Distance3DOp(left, right).distance();
- }
-
- public static double length (Geometry geometry){
- return geometry.getLength();
- }
-
- public static Geometry normalize (Geometry geometry){
- geometry.normalize();
- return geometry;
- }
-
- public static Double x(Geometry geometry) {
- if (geometry instanceof Point) {
- return geometry.getCoordinate().x;
- }
- return null;
- }
-
- public static Double y(Geometry geometry) {
- if (geometry instanceof Point) {
- return geometry.getCoordinate().y;
- }
- return null;
- }
-
- public static Double z(Geometry geometry) {
- if (geometry instanceof Point) {
- return geometry.getCoordinate().z;
- }
- return null;
- }
-
- public static Double m(Geometry geom) {
- if (geom instanceof Point) {
- return geom.getCoordinate().getM();
- }
- return null;
- }
-
- public static Double mMin(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double min = Double.MAX_VALUE;
- for(int i=0; i < points.length; i++){
- if(Double.isNaN(points[i].getM()))
- continue;
- min = Math.min(points[i].getM(), min);
- }
- return min == Double.MAX_VALUE ? null : min;
- }
-
- public static Double mMax(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double max = - Double.MAX_VALUE;
- for (int i=0; i < points.length; i++) {
- if(Double.isNaN(points[i].getM()))
- continue;
- max = Math.max(points[i].getM(), max);
- }
- return max == -Double.MAX_VALUE ? null : max;
- }
-
- public static double xMin(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double min = Double.MAX_VALUE;
- for(int i=0; i < points.length; i++){
- min = Math.min(points[i].getX(), min);
- }
- return min;
- }
-
- public static double xMax(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double max = - Double.MAX_VALUE;
- for (int i=0; i < points.length; i++) {
- max = Math.max(points[i].getX(), max);
- }
- return max;
- }
-
- public static double yMin(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double min = Double.MAX_VALUE;
- for(int i=0; i < points.length; i++){
- min = Math.min(points[i].getY(), min);
- }
- return min;
- }
-
- public static double yMax(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double max = - Double.MAX_VALUE;
- for (int i=0; i < points.length; i++) {
- max = Math.max(points[i].getY(), max);
- }
- return max;
- }
-
- public static Double zMax(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double max = - Double.MAX_VALUE;
- for (int i=0; i < points.length; i++) {
- if(Double.isNaN(points[i].getZ()))
- continue;
- max = Math.max(points[i].getZ(), max);
- }
- return max == -Double.MAX_VALUE ? null : max;
- }
-
- public static Double zMin(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- double min = Double.MAX_VALUE;
- for(int i=0; i < points.length; i++){
- if(Double.isNaN(points[i].getZ()))
- continue;
- min = Math.min(points[i].getZ(), min);
- }
- return min == Double.MAX_VALUE ? null : min;
- }
-
- public static boolean hasM(Geometry geom) {
- Coordinate coord = geom.getCoordinate();
- return !Double.isNaN(coord.getM());
- }
-
- public static boolean hasZ(Geometry geom) {
- Coordinate coord = geom.getCoordinate();
- return !Double.isNaN(coord.getZ());
- }
-
- public static Geometry flipCoordinates(Geometry geometry) {
- GeomUtils.flipCoordinates(geometry);
- return geometry;
- }
-
- public static String geohash(Geometry geometry, int precision) {
- return GeometryGeoHashEncoder.calculate(geometry, precision);
- }
-
- public static Geometry pointOnSurface(Geometry geometry) {
- return GeomUtils.getInteriorPoint(geometry);
- }
-
- public static Geometry reverse(Geometry geometry) {
- return geometry.reverse();
- }
-
- public static Geometry geometryN(Geometry geometry, int n) {
- if (n < geometry.getNumGeometries()) {
- return geometry.getGeometryN(n);
- }
- return null;
- }
-
- public static Geometry interiorRingN(Geometry geometry, int n) {
- if (geometry instanceof Polygon) {
- Polygon polygon = (Polygon) geometry;
- if (n < polygon.getNumInteriorRing()) {
- Geometry interiorRing = polygon.getInteriorRingN(n);
- if (interiorRing instanceof LinearRing) {
- interiorRing = GEOMETRY_FACTORY.createLineString(interiorRing.getCoordinates());
- }
- return interiorRing;
+ geometry.apply(filter);
+ return filter.isDone();
+ }
+
+ public static Geometry shiftLongitude(Geometry geometry) {
+ geometry.apply(
+ new CoordinateSequenceFilter() {
+ @Override
+ public void filter(CoordinateSequence seq, int i) {
+ double newX = seq.getX(i);
+ if (newX < 0) {
+ newX += 360;
+ } else if (newX > 180) {
+ newX -= 360;
}
- }
- return null;
- }
-
- public static Geometry pointN(Geometry geometry, int n) {
- if(!(geometry instanceof LineString)) {
- return null;
- }
- return GeomUtils.getNthPoint((LineString)geometry, n);
- }
-
- public static Geometry exteriorRing(Geometry geometry) {
- Geometry ring = GeomUtils.getExteriorRing(geometry);
- if (ring instanceof LinearRing) {
- ring = GEOMETRY_FACTORY.createLineString(ring.getCoordinates());
- }
- return ring;
- }
-
- public static String asEWKT(Geometry geometry) {
- return GeomUtils.getEWKT(geometry);
- }
-
- public static String asWKT(Geometry geometry) {
- return GeomUtils.getWKT(geometry);
- }
-
- public static byte[] asEWKB(Geometry geometry) {
- return GeomUtils.getEWKB(geometry);
- }
-
- public static String asHexEWKB(Geometry geom, String endian) {
- if (endian.equalsIgnoreCase("NDR")) {
- return GeomUtils.getHexEWKB(geom, ByteOrderValues.LITTLE_ENDIAN);
- } else if (endian.equalsIgnoreCase("XDR")) {
- return GeomUtils.getHexEWKB(geom, ByteOrderValues.BIG_ENDIAN);
- }
- throw new IllegalArgumentException("You must select either NDR (little-endian) or XDR (big-endian) as the endian format.");
- }
-
- public static String asHexEWKB(Geometry geom) {
- return asHexEWKB(geom, "NDR");
- }
-
- public static byte[] asWKB(Geometry geometry) {
- return GeomUtils.getWKB(geometry);
- }
-
- public static String asGeoJson(Geometry geometry) {
- if (geometry == null) {
- return null;
- }
- GeoJSONWriter writer = new GeoJSONWriter();
- return writer.write(geometry).toString();
- }
-
- public static int nPoints(Geometry geometry) {
- return geometry.getNumPoints();
- }
-
- public static int nDims(Geometry geometry) {
- int count_dimension =0;
- Coordinate geom = geometry.getCoordinate();
- Double x_cord = geom.getX();
- Double y_cord = geom.getY();
- Double z_cord = geom.getZ();
- Double m_cord = geom.getM();
- if(!Double.isNaN(x_cord))
- count_dimension++;
- if(!Double.isNaN(y_cord))
- count_dimension++;
- if(!Double.isNaN(z_cord))
- count_dimension++;
- if(!Double.isNaN(m_cord))
- count_dimension++;
- return count_dimension;
- }
-
- public static int numGeometries(Geometry geometry) {
- return geometry.getNumGeometries();
- }
-
- public static Integer numInteriorRings(Geometry geometry) {
- if (geometry instanceof Polygon) {
- return ((Polygon) geometry).getNumInteriorRing();
- }
- return null;
- }
-
- public static String asGML(Geometry geometry) {
- return new GMLWriter().write(geometry);
- }
-
- public static String asKML(Geometry geometry) {
- return new KMLWriter().write(geometry);
- }
-
- public static Geometry force2D(Geometry geometry) {
- return GeomUtils.get2dGeom(geometry);
- }
-
- public static boolean isEmpty(Geometry geometry) {
- return geometry.isEmpty();
- }
-
- public static Geometry buildArea(Geometry geometry) {
- return GeomUtils.buildArea(geometry);
- }
-
- public static Geometry setSRID(Geometry geometry, int srid) {
- if (geometry == null) {
- return null;
- }
- GeometryFactory factory = new GeometryFactory(geometry.getPrecisionModel(), srid, geometry.getFactory().getCoordinateSequenceFactory());
- return factory.createGeometry(geometry);
- }
-
- public static int getSRID(Geometry geometry) {
- if (geometry == null) {
- return 0;
- }
- return geometry.getSRID();
- }
+ seq.setOrdinate(i, CoordinateSequence.X, newX);
+ }
- public static boolean isClosed(Geometry geometry) {
- if (geometry instanceof Circle || geometry instanceof MultiPoint || geometry instanceof MultiPolygon || geometry instanceof Point || geometry instanceof Polygon) {
- return true;
- } else if (geometry instanceof LineString) {
- return ((LineString) geometry).isClosed();
- } else if (geometry instanceof MultiLineString) {
- return ((MultiLineString) geometry).isClosed();
- } else if (geometry instanceof GeometryCollection) {
+ @Override
+ public boolean isDone() {
return false;
- }
- return false;
- }
-
- public static boolean isRing(Geometry geometry) {
- return geometry instanceof LineString && ((LineString) geometry).isClosed() && geometry.isSimple();
- }
-
- public static boolean isSimple(Geometry geometry) {
- return new IsSimpleOp(geometry).isSimple();
- }
+ }
- public static boolean isValid(Geometry geometry) {
- return isValid(geometry, OGC_SFS_VALIDITY);
- }
-
- public static boolean isValid(Geometry geom, int flag) {
- IsValidOp isValidOp = new IsValidOp(geom);
-
- // Set the validity model based on flags
- if (flag == ESRI_VALIDITY) {
- isValidOp.setSelfTouchingRingFormingHoleValid(true);
+ @Override
+ public boolean isGeometryChanged() {
+ return true;
+ }
+ });
+ return geometry;
+ }
+
+ public static Geometry envelope(Geometry geometry) {
+ return geometry.getEnvelope();
+ }
+
+ public static double distance(Geometry left, Geometry right) {
+ return left.distance(right);
+ }
+
+ public static double distance3d(Geometry left, Geometry right) {
+ return new Distance3DOp(left, right).distance();
+ }
+
+ public static double length(Geometry geometry) {
+ return geometry.getLength();
+ }
+
+ public static Geometry normalize(Geometry geometry) {
+ geometry.normalize();
+ return geometry;
+ }
+
+ public static Double x(Geometry geometry) {
+ if (geometry instanceof Point) {
+ return geometry.getCoordinate().x;
+ }
+ return null;
+ }
+
+ public static Double y(Geometry geometry) {
+ if (geometry instanceof Point) {
+ return geometry.getCoordinate().y;
+ }
+ return null;
+ }
+
+ public static Double z(Geometry geometry) {
+ if (geometry instanceof Point) {
+ return geometry.getCoordinate().z;
+ }
+ return null;
+ }
+
+ public static Double m(Geometry geom) {
+ if (geom instanceof Point) {
+ return geom.getCoordinate().getM();
+ }
+ return null;
+ }
+
+ public static Double mMin(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double min = Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ if (Double.isNaN(points[i].getM())) continue;
+ min = Math.min(points[i].getM(), min);
+ }
+ return min == Double.MAX_VALUE ? null : min;
+ }
+
+ public static Double mMax(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double max = -Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ if (Double.isNaN(points[i].getM())) continue;
+ max = Math.max(points[i].getM(), max);
+ }
+ return max == -Double.MAX_VALUE ? null : max;
+ }
+
+ public static double xMin(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double min = Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ min = Math.min(points[i].getX(), min);
+ }
+ return min;
+ }
+
+ public static double xMax(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double max = -Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ max = Math.max(points[i].getX(), max);
+ }
+ return max;
+ }
+
+ public static double yMin(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double min = Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ min = Math.min(points[i].getY(), min);
+ }
+ return min;
+ }
+
+ public static double yMax(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double max = -Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ max = Math.max(points[i].getY(), max);
+ }
+ return max;
+ }
+
+ public static Double zMax(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double max = -Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ if (Double.isNaN(points[i].getZ())) continue;
+ max = Math.max(points[i].getZ(), max);
+ }
+ return max == -Double.MAX_VALUE ? null : max;
+ }
+
+ public static Double zMin(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ double min = Double.MAX_VALUE;
+ for (int i = 0; i < points.length; i++) {
+ if (Double.isNaN(points[i].getZ())) continue;
+ min = Math.min(points[i].getZ(), min);
+ }
+ return min == Double.MAX_VALUE ? null : min;
+ }
+
+ public static boolean hasM(Geometry geom) {
+ Coordinate coord = geom.getCoordinate();
+ return !Double.isNaN(coord.getM());
+ }
+
+ public static boolean hasZ(Geometry geom) {
+ Coordinate coord = geom.getCoordinate();
+ return !Double.isNaN(coord.getZ());
+ }
+
+ public static Geometry flipCoordinates(Geometry geometry) {
+ GeomUtils.flipCoordinates(geometry);
+ return geometry;
+ }
+
+ public static String geohash(Geometry geometry, int precision) {
+ return GeometryGeoHashEncoder.calculate(geometry, precision);
+ }
+
+ public static Geometry pointOnSurface(Geometry geometry) {
+ return GeomUtils.getInteriorPoint(geometry);
+ }
+
+ public static Geometry reverse(Geometry geometry) {
+ return geometry.reverse();
+ }
+
+ public static Geometry geometryN(Geometry geometry, int n) {
+ if (n < geometry.getNumGeometries()) {
+ return geometry.getGeometryN(n);
+ }
+ return null;
+ }
+
+ public static Geometry interiorRingN(Geometry geometry, int n) {
+ if (geometry instanceof Polygon) {
+ Polygon polygon = (Polygon) geometry;
+ if (n < polygon.getNumInteriorRing()) {
+ Geometry interiorRing = polygon.getInteriorRingN(n);
+ if (interiorRing instanceof LinearRing) {
+ interiorRing = GEOMETRY_FACTORY.createLineString(interiorRing.getCoordinates());
+ }
+ return interiorRing;
+ }
+ }
+ return null;
+ }
+
+ public static Geometry pointN(Geometry geometry, int n) {
+ if (!(geometry instanceof LineString)) {
+ return null;
+ }
+ return GeomUtils.getNthPoint((LineString) geometry, n);
+ }
+
+ public static Geometry exteriorRing(Geometry geometry) {
+ Geometry ring = GeomUtils.getExteriorRing(geometry);
+ if (ring instanceof LinearRing) {
+ ring = GEOMETRY_FACTORY.createLineString(ring.getCoordinates());
+ }
+ return ring;
+ }
+
+ public static String asEWKT(Geometry geometry) {
+ return GeomUtils.getEWKT(geometry);
+ }
+
+ public static String asWKT(Geometry geometry) {
+ return GeomUtils.getWKT(geometry);
+ }
+
+ public static byte[] asEWKB(Geometry geometry) {
+ return GeomUtils.getEWKB(geometry);
+ }
+
+ public static String asHexEWKB(Geometry geom, String endian) {
+ if (endian.equalsIgnoreCase("NDR")) {
+ return GeomUtils.getHexEWKB(geom, ByteOrderValues.LITTLE_ENDIAN);
+ } else if (endian.equalsIgnoreCase("XDR")) {
+ return GeomUtils.getHexEWKB(geom, ByteOrderValues.BIG_ENDIAN);
+ }
+ throw new IllegalArgumentException(
+ "You must select either NDR (little-endian) or XDR (big-endian) as the endian format.");
+ }
+
+ public static String asHexEWKB(Geometry geom) {
+ return asHexEWKB(geom, "NDR");
+ }
+
+ public static byte[] asWKB(Geometry geometry) {
+ return GeomUtils.getWKB(geometry);
+ }
+
+ public static String asGeoJson(Geometry geometry) {
+ if (geometry == null) {
+ return null;
+ }
+ GeoJSONWriter writer = new GeoJSONWriter();
+ return writer.write(geometry).toString();
+ }
+
+ public static int nPoints(Geometry geometry) {
+ return geometry.getNumPoints();
+ }
+
+ public static int nDims(Geometry geometry) {
+ int count_dimension = 0;
+ Coordinate geom = geometry.getCoordinate();
+ Double x_cord = geom.getX();
+ Double y_cord = geom.getY();
+ Double z_cord = geom.getZ();
+ Double m_cord = geom.getM();
+ if (!Double.isNaN(x_cord)) count_dimension++;
+ if (!Double.isNaN(y_cord)) count_dimension++;
+ if (!Double.isNaN(z_cord)) count_dimension++;
+ if (!Double.isNaN(m_cord)) count_dimension++;
+ return count_dimension;
+ }
+
+ public static int numGeometries(Geometry geometry) {
+ return geometry.getNumGeometries();
+ }
+
+ public static Integer numInteriorRings(Geometry geometry) {
+ if (geometry instanceof Polygon) {
+ return ((Polygon) geometry).getNumInteriorRing();
+ }
+ return null;
+ }
+
+ public static String asGML(Geometry geometry) {
+ return new GMLWriter().write(geometry);
+ }
+
+ public static String asKML(Geometry geometry) {
+ return new KMLWriter().write(geometry);
+ }
+
+ public static Geometry force2D(Geometry geometry) {
+ return GeomUtils.get2dGeom(geometry);
+ }
+
+ public static boolean isEmpty(Geometry geometry) {
+ return geometry.isEmpty();
+ }
+
+ public static Geometry buildArea(Geometry geometry) {
+ return GeomUtils.buildArea(geometry);
+ }
+
+ public static Geometry setSRID(Geometry geometry, int srid) {
+ if (geometry == null) {
+ return null;
+ }
+ GeometryFactory factory =
+ new GeometryFactory(
+ geometry.getPrecisionModel(),
+ srid,
+ geometry.getFactory().getCoordinateSequenceFactory());
+ return factory.createGeometry(geometry);
+ }
+
+ public static int getSRID(Geometry geometry) {
+ if (geometry == null) {
+ return 0;
+ }
+ return geometry.getSRID();
+ }
+
+ public static boolean isClosed(Geometry geometry) {
+ if (geometry instanceof Circle
+ || geometry instanceof MultiPoint
+ || geometry instanceof MultiPolygon
+ || geometry instanceof Point
+ || geometry instanceof Polygon) {
+ return true;
+ } else if (geometry instanceof LineString) {
+ return ((LineString) geometry).isClosed();
+ } else if (geometry instanceof MultiLineString) {
+ return ((MultiLineString) geometry).isClosed();
+ } else if (geometry instanceof GeometryCollection) {
+ return false;
+ }
+ return false;
+ }
+
+ public static boolean isRing(Geometry geometry) {
+ return geometry instanceof LineString
+ && ((LineString) geometry).isClosed()
+ && geometry.isSimple();
+ }
+
+ public static boolean isSimple(Geometry geometry) {
+ return new IsSimpleOp(geometry).isSimple();
+ }
+
+ public static boolean isValid(Geometry geometry) {
+ return isValid(geometry, OGC_SFS_VALIDITY);
+ }
+
+ public static boolean isValid(Geometry geom, int flag) {
+ IsValidOp isValidOp = new IsValidOp(geom);
+
+ // Set the validity model based on flags
+ if (flag == ESRI_VALIDITY) {
+ isValidOp.setSelfTouchingRingFormingHoleValid(true);
+ } else {
+ isValidOp.setSelfTouchingRingFormingHoleValid(false);
+ }
+
+ return isValidOp.isValid();
+ }
+
+ public static Geometry addPoint(Geometry linestring, Geometry point) {
+ return addPoint(linestring, point, -1);
+ }
+
+ public static Geometry addPoint(Geometry linestring, Geometry point, int position) {
+ if (linestring instanceof LineString && point instanceof Point) {
+ List<Coordinate> coordinates = new ArrayList<>(Arrays.asList(linestring.getCoordinates()));
+ if (-1 <= position && position <= coordinates.size()) {
+ if (position < 0) {
+ coordinates.add(point.getCoordinate());
} else {
- isValidOp.setSelfTouchingRingFormingHoleValid(false);
- }
-
- return isValidOp.isValid();
- }
-
- public static Geometry addPoint(Geometry linestring, Geometry point) {
- return addPoint(linestring, point, -1);
- }
-
- public static Geometry addPoint(Geometry linestring, Geometry point, int position) {
- if (linestring instanceof LineString && point instanceof Point) {
- List<Coordinate> coordinates = new ArrayList<>(Arrays.asList(linestring.getCoordinates()));
- if (-1 <= position && position <= coordinates.size()) {
- if (position < 0) {
- coordinates.add(point.getCoordinate());
- } else {
- coordinates.add(position, point.getCoordinate());
- }
- return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
- }
+ coordinates.add(position, point.getCoordinate());
}
- return null;
+ return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
+ }
}
+ return null;
+ }
- public static Geometry removePoint(Geometry linestring) {
- if (linestring != null) {
- return removePoint(linestring, -1);
- }
- return null;
- }
-
- public static Geometry removePoint(Geometry linestring, int position) {
- if (linestring instanceof LineString) {
- List<Coordinate> coordinates = new ArrayList<>(Arrays.asList(linestring.getCoordinates()));
- if (2 < coordinates.size() && position < coordinates.size()) {
- if (position == -1) {
- position = coordinates.size() - 1;
- }
- coordinates.remove(position);
- return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
- }
- }
- return null;
- }
-
- public static Geometry setPoint(Geometry linestring, int position, Geometry point) {
- if (linestring instanceof LineString) {
- List<Coordinate> coordinates = new ArrayList<>(Arrays.asList(linestring.getCoordinates()));
- if (-coordinates.size() <= position && position < coordinates.size()) {
- if (position < 0) {
- coordinates.set(coordinates.size() + position, point.getCoordinate());
- } else {
- coordinates.set(position, point.getCoordinate());
- }
- return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
- }
- }
- return null;
+ public static Geometry removePoint(Geometry linestring) {
+ if (linestring != null) {
+ return removePoint(linestring, -1);
}
+ return null;
+ }
- public static Geometry lineFromMultiPoint(Geometry geometry) {
- if(!(geometry instanceof MultiPoint)) {
- return null;
- }
- List<Coordinate> coordinates = new ArrayList<>();
- for(Coordinate c : geometry.getCoordinates()){
- coordinates.add(c);
+ public static Geometry removePoint(Geometry linestring, int position) {
+ if (linestring instanceof LineString) {
+ List<Coordinate> coordinates = new ArrayList<>(Arrays.asList(linestring.getCoordinates()));
+ if (2 < coordinates.size() && position < coordinates.size()) {
+ if (position == -1) {
+ position = coordinates.size() - 1;
}
+ coordinates.remove(position);
return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
+ }
}
+ return null;
+ }
- public static Geometry closestPoint(Geometry left, Geometry right) {
- DistanceOp distanceOp = new DistanceOp(left, right);
- try {
- Coordinate[] closestPoints = distanceOp.nearestPoints();
- return GEOMETRY_FACTORY.createPoint(closestPoints[0]);
- }
- catch (Exception e) {
- throw new IllegalArgumentException("ST_ClosestPoint doesn't support empty geometry object.");
- }
- }
-
- public static Geometry delaunayTriangle(Geometry geometry) {
- return delaunayTriangle(geometry, 0.0, 0);
- }
-
- public static Geometry delaunayTriangle(Geometry geometry, double tolerance) {
- return delaunayTriangle(geometry, tolerance, 0);
- }
-
- public static Geometry delaunayTriangle(Geometry geometry, double tolerance, int flag) {
- DelaunayTriangulationBuilder dTBuilder = new DelaunayTriangulationBuilder();
- dTBuilder.setSites(geometry);
- dTBuilder.setTolerance(tolerance);
- if (flag == 0) {
- return dTBuilder.getTriangles(geometry.getFactory());
- } else if (flag == 1) {
- return dTBuilder.getEdges(geometry.getFactory());
+ public static Geometry setPoint(Geometry linestring, int position, Geometry point) {
+ if (linestring instanceof LineString) {
+ List<Coordinate> coordinates = new ArrayList<>(Arrays.asList(linestring.getCoordinates()));
+ if (-coordinates.size() <= position && position < coordinates.size()) {
+ if (position < 0) {
+ coordinates.set(coordinates.size() + position, point.getCoordinate());
} else {
- throw new IllegalArgumentException("Select a valid flag option (0 or 1).");
- }
- }
-
- public static int zmFlag(Geometry geom) {
- Coordinate coords = geom.getCoordinate();
- boolean hasZ = !Double.isNaN(coords.getZ());
- boolean hasM = !Double.isNaN(coords.getM());
- if (hasM && hasZ) {
- // geom is 4D
- return 3;
- } else if (hasZ) {
- // geom is 3D-Z
- return 2;
- } else if (hasM) {
- // geom is 3D-M
- return 1;
- }
- // geom is 2D
- return 0;
- }
-
- public static Geometry concaveHull(Geometry geometry, double pctConvex, boolean allowHoles){
- ConcaveHull concave_hull = new ConcaveHull(geometry);
- concave_hull.setMaximumEdgeLengthRatio(pctConvex);
- concave_hull.setHolesAllowed(allowHoles);
-
- return concave_hull.getHull();
- }
-
- public static Geometry convexHull(Geometry geometry) {
- return geometry.convexHull();
- }
-
- public static Geometry getCentroid(Geometry geometry) {
- return geometry.getCentroid();
- }
-
- public static Geometry intersection(Geometry leftGeometry, Geometry rightGeometry) {
- boolean isIntersects = leftGeometry.intersects(rightGeometry);
- if (!isIntersects) {
- return EMPTY_POLYGON;
- }
- if (leftGeometry.contains(rightGeometry)) {
- return rightGeometry;
- }
- if (rightGeometry.contains(leftGeometry)) {
- return leftGeometry;
- }
- return leftGeometry.intersection(rightGeometry);
- }
-
- public static Geometry makeValid(Geometry geometry, boolean keepCollapsed) {
- GeometryFixer fixer = new GeometryFixer(geometry);
- fixer.setKeepCollapsed(keepCollapsed);
- return fixer.getResult();
- }
-
- public static Geometry reducePrecision(Geometry geometry, int precisionScale) {
- GeometryPrecisionReducer precisionReduce = new GeometryPrecisionReducer(new PrecisionModel(Math.pow(10, precisionScale)));
- return precisionReduce.reduce(geometry);
- }
-
- public static Geometry lineMerge(Geometry geometry) {
- if (geometry instanceof MultiLineString) {
- MultiLineString multiLineString = (MultiLineString) geometry;
- int numLineStrings = multiLineString.getNumGeometries();
- LineMerger merger = new LineMerger();
- for (int k = 0; k < numLineStrings; k++) {
- LineString line = (LineString) multiLineString.getGeometryN(k);
- merger.add(line);
- }
- if (merger.getMergedLineStrings().size() == 1) {
- // If the merger was able to join the lines, there will be only one element
- return (Geometry) merger.getMergedLineStrings().iterator().next();
- } else {
- // if the merger couldn't join the lines, it will contain the individual lines, so return the input
- return geometry;
- }
+ coordinates.set(position, point.getCoordinate());
}
- return EMPTY_GEOMETRY_COLLECTION;
- }
-
- public static Geometry minimumBoundingCircle(Geometry geometry, int quadrantSegments) {
- MinimumBoundingCircle minimumBoundingCircle = new MinimumBoundingCircle(geometry);
- Coordinate centre = minimumBoundingCircle.getCentre();
- double radius = minimumBoundingCircle.getRadius();
- Geometry circle = null;
- if (centre == null) {
- circle = geometry.getFactory().createPolygon();
+ return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
+ }
+ }
+ return null;
+ }
+
+ public static Geometry lineFromMultiPoint(Geometry geometry) {
+ if (!(geometry instanceof MultiPoint)) {
+ return null;
+ }
+ List<Coordinate> coordinates = new ArrayList<>();
+ for (Coordinate c : geometry.getCoordinates()) {
+ coordinates.add(c);
+ }
+ return GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0]));
+ }
+
+ public static Geometry closestPoint(Geometry left, Geometry right) {
+ DistanceOp distanceOp = new DistanceOp(left, right);
+ try {
+ Coordinate[] closestPoints = distanceOp.nearestPoints();
+ return GEOMETRY_FACTORY.createPoint(closestPoints[0]);
+ } catch (Exception e) {
+ throw new IllegalArgumentException("ST_ClosestPoint doesn't support empty geometry object.");
+ }
+ }
+
+ public static Geometry delaunayTriangle(Geometry geometry) {
+ return delaunayTriangle(geometry, 0.0, 0);
+ }
+
+ public static Geometry delaunayTriangle(Geometry geometry, double tolerance) {
+ return delaunayTriangle(geometry, tolerance, 0);
+ }
+
+ public static Geometry delaunayTriangle(Geometry geometry, double tolerance, int flag) {
+ DelaunayTriangulationBuilder dTBuilder = new DelaunayTriangulationBuilder();
+ dTBuilder.setSites(geometry);
+ dTBuilder.setTolerance(tolerance);
+ if (flag == 0) {
+ return dTBuilder.getTriangles(geometry.getFactory());
+ } else if (flag == 1) {
+ return dTBuilder.getEdges(geometry.getFactory());
+ } else {
+ throw new IllegalArgumentException("Select a valid flag option (0 or 1).");
+ }
+ }
+
+ public static int zmFlag(Geometry geom) {
+ Coordinate coords = geom.getCoordinate();
+ boolean hasZ = !Double.isNaN(coords.getZ());
+ boolean hasM = !Double.isNaN(coords.getM());
+ if (hasM && hasZ) {
+ // geom is 4D
+ return 3;
+ } else if (hasZ) {
+ // geom is 3D-Z
+ return 2;
+ } else if (hasM) {
+ // geom is 3D-M
+ return 1;
+ }
+ // geom is 2D
+ return 0;
+ }
+
+ public static Geometry concaveHull(Geometry geometry, double pctConvex, boolean allowHoles) {
+ ConcaveHull concave_hull = new ConcaveHull(geometry);
+ concave_hull.setMaximumEdgeLengthRatio(pctConvex);
+ concave_hull.setHolesAllowed(allowHoles);
+
+ return concave_hull.getHull();
+ }
+
+ public static Geometry convexHull(Geometry geometry) {
+ return geometry.convexHull();
+ }
+
+ public static Geometry getCentroid(Geometry geometry) {
+ return geometry.getCentroid();
+ }
+
+ public static Geometry intersection(Geometry leftGeometry, Geometry rightGeometry) {
+ boolean isIntersects = leftGeometry.intersects(rightGeometry);
+ if (!isIntersects) {
+ return EMPTY_POLYGON;
+ }
+ if (leftGeometry.contains(rightGeometry)) {
+ return rightGeometry;
+ }
+ if (rightGeometry.contains(leftGeometry)) {
+ return leftGeometry;
+ }
+ return leftGeometry.intersection(rightGeometry);
+ }
+
+ public static Geometry makeValid(Geometry geometry, boolean keepCollapsed) {
+ GeometryFixer fixer = new GeometryFixer(geometry);
+ fixer.setKeepCollapsed(keepCollapsed);
+ return fixer.getResult();
+ }
+
+ public static Geometry reducePrecision(Geometry geometry, int precisionScale) {
+ GeometryPrecisionReducer precisionReduce =
+ new GeometryPrecisionReducer(new PrecisionModel(Math.pow(10, precisionScale)));
+ return precisionReduce.reduce(geometry);
+ }
+
+ public static Geometry lineMerge(Geometry geometry) {
+ if (geometry instanceof MultiLineString) {
+ MultiLineString multiLineString = (MultiLineString) geometry;
+ int numLineStrings = multiLineString.getNumGeometries();
+ LineMerger merger = new LineMerger();
+ for (int k = 0; k < numLineStrings; k++) {
+ LineString line = (LineString) multiLineString.getGeometryN(k);
+ merger.add(line);
+ }
+ if (merger.getMergedLineStrings().size() == 1) {
+ // If the merger was able to join the lines, there will be only one element
+ return (Geometry) merger.getMergedLineStrings().iterator().next();
+ } else {
+ // if the merger couldn't join the lines, it will contain the individual lines, so return
+ // the input
+ return geometry;
+ }
+ }
+ return EMPTY_GEOMETRY_COLLECTION;
+ }
+
+ public static Geometry minimumBoundingCircle(Geometry geometry, int quadrantSegments) {
+ MinimumBoundingCircle minimumBoundingCircle = new MinimumBoundingCircle(geometry);
+ Coordinate centre = minimumBoundingCircle.getCentre();
+ double radius = minimumBoundingCircle.getRadius();
+ Geometry circle = null;
+ if (centre == null) {
+ circle = geometry.getFactory().createPolygon();
+ } else {
+ circle = geometry.getFactory().createPoint(centre);
+ if (radius != 0D) {
+ circle = circle.buffer(radius, quadrantSegments);
+ }
+ }
+ return circle;
+ }
+
+ public static Pair<Geometry, Double> minimumBoundingRadius(Geometry geometry) {
+ MinimumBoundingCircle minimumBoundingCircle = new MinimumBoundingCircle(geometry);
+ Coordinate coods = minimumBoundingCircle.getCentre();
+ double radius = minimumBoundingCircle.getRadius();
+ Point centre = GEOMETRY_FACTORY.createPoint(coods);
+ return Pair.of(centre, radius);
+ }
+
+ public static double minimumClearance(Geometry geometry) {
+ return MinimumClearance.getDistance(geometry);
+ }
+
+ public static Geometry minimumClearanceLine(Geometry geometry) {
+ return MinimumClearance.getLine(geometry);
+ }
+
+ public static Geometry lineSubString(Geometry geom, double fromFraction, double toFraction) {
+ double length = geom.getLength();
+ LengthIndexedLine indexedLine = new LengthIndexedLine(geom);
+ Geometry subLine = indexedLine.extractLine(length * fromFraction, length * toFraction);
+ return subLine;
+ }
+
+ public static Geometry lineInterpolatePoint(Geometry geom, double fraction) {
+ double length = geom.getLength();
+ LengthIndexedLine indexedLine = new LengthIndexedLine(geom);
+ Coordinate interPoint = indexedLine.extractPoint(length * fraction);
+ return GEOMETRY_FACTORY.createPoint(interPoint);
+ }
+
+ /**
+ * Forces a Polygon/MultiPolygon to use clockwise orientation for the exterior ring and a
+ * counter-clockwise for the interior ring(s).
+ *
+ * @param geom
+ * @return a clockwise orientated (Multi)Polygon
+ */
+ public static Geometry forcePolygonCW(Geometry geom) {
+ if (isPolygonCW(geom)) {
+ return geom;
+ }
+
+ if (geom instanceof Polygon) {
+ return transformCW((Polygon) geom);
+
+ } else if (geom instanceof MultiPolygon) {
+ List<Polygon> polygons = new ArrayList<>();
+ for (int i = 0; i < geom.getNumGeometries(); i++) {
+ Polygon polygon = (Polygon) geom.getGeometryN(i);
+ polygons.add((Polygon) transformCW(polygon));
+ }
+
+ return new GeometryFactory().createMultiPolygon(polygons.toArray(new Polygon[0]));
+ }
+ // Non-polygonal geometries are returned unchanged
+ return geom;
+ }
+
+ private static Geometry transformCW(Polygon polygon) {
+ LinearRing exteriorRing = polygon.getExteriorRing();
+ LinearRing exteriorRingEnforced = transformCW(exteriorRing, true);
+
+ List<LinearRing> interiorRings = new ArrayList<>();
+ for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
+ interiorRings.add(transformCW(polygon.getInteriorRingN(i), false));
+ }
+
+ return new GeometryFactory(polygon.getPrecisionModel(), polygon.getSRID())
+ .createPolygon(exteriorRingEnforced, interiorRings.toArray(new LinearRing[0]));
+ }
+
+ private static LinearRing transformCW(LinearRing ring, boolean isExteriorRing) {
+ boolean isRingClockwise = !Orientation.isCCW(ring.getCoordinateSequence());
+
+ LinearRing enforcedRing;
+ if (isExteriorRing) {
+ enforcedRing = isRingClockwise ? (LinearRing) ring.copy() : ring.reverse();
+ } else {
+ enforcedRing = isRingClockwise ? ring.reverse() : (LinearRing) ring.copy();
+ }
+ return enforcedRing;
+ }
+
+ /**
+ * This function accepts Polygon and MultiPolygon, if any other type is provided then it will
+ * return false. If the exterior ring is clockwise and the interior ring(s) are counter-clockwise
+ * then returns true, otherwise false.
+ *
+ * @param geom Polygon or MultiPolygon
+ * @return
+ */
+ public static boolean isPolygonCW(Geometry geom) {
+ if (geom instanceof MultiPolygon) {
+ MultiPolygon multiPolygon = (MultiPolygon) geom;
+
+ boolean arePolygonsCW = checkIfPolygonCW((Polygon) multiPolygon.getGeometryN(0));
+ for (int i = 1; i < multiPolygon.getNumGeometries(); i++) {
+ arePolygonsCW = arePolygonsCW && checkIfPolygonCW((Polygon) multiPolygon.getGeometryN(i));
+ }
+ return arePolygonsCW;
+ } else if (geom instanceof Polygon) {
+ return checkIfPolygonCW((Polygon) geom);
+ }
+ // False for remaining geometry types
+ return false;
+ }
+
+ private static boolean checkIfPolygonCW(Polygon geom) {
+ LinearRing exteriorRing = geom.getExteriorRing();
+ boolean isExteriorRingCW = !Orientation.isCCW(exteriorRing.getCoordinateSequence());
+
+ boolean isInteriorRingCW = Orientation.isCCW(geom.getInteriorRingN(0).getCoordinateSequence());
+ for (int i = 1; i < geom.getNumInteriorRing(); i++) {
+ isInteriorRingCW =
+ isInteriorRingCW && Orientation.isCCW(geom.getInteriorRingN(i).getCoordinateSequence());
+ }
+
+ return isExteriorRingCW && isInteriorRingCW;
+ }
+
+ public static Geometry triangulatePolygon(Geometry geom) {
+ return ConstrainedDelaunayTriangulator.triangulate(geom);
+ }
+
+ public static double lineLocatePoint(Geometry geom, Geometry point) {
+ double length = geom.getLength();
+ LengthIndexedLine indexedLine = new LengthIndexedLine(geom);
+ return indexedLine.indexOf(point.getCoordinate()) / length;
+ }
+
+ public static Geometry locateAlong(Geometry linear, double measure, double offset) {
+ return GeometryLocateAlongProcessor.processGeometry(linear, measure, offset);
+ }
+
+ public static Geometry locateAlong(Geometry linear, double measure) {
+ return locateAlong(linear, measure, 0);
+ }
+
+ /**
+ * Forces a Polygon/MultiPolygon to use counter-clockwise orientation for the exterior ring and a
+ * clockwise for the interior ring(s).
+ *
+ * @param geom
+ * @return a counter-clockwise orientated (Multi)Polygon
+ */
+ public static Geometry forcePolygonCCW(Geometry geom) {
+ if (isPolygonCCW(geom)) {
+ return geom;
+ }
+
+ if (geom instanceof Polygon) {
+ return transformCCW((Polygon) geom);
+
+ } else if (geom instanceof MultiPolygon) {
+ List<Polygon> polygons = new ArrayList<>();
+ for (int i = 0; i < geom.getNumGeometries(); i++) {
+ Polygon polygon = (Polygon) geom.getGeometryN(i);
+ polygons.add((Polygon) transformCCW(polygon));
+ }
+
+ return new GeometryFactory().createMultiPolygon(polygons.toArray(new Polygon[0]));
+ }
+ // Non-polygonal geometries are returned unchanged
+ return geom;
+ }
+
+ private static Geometry transformCCW(Polygon polygon) {
+ LinearRing exteriorRing = polygon.getExteriorRing();
+ LinearRing exteriorRingEnforced = transformCCW(exteriorRing, true);
+
+ List<LinearRing> interiorRings = new ArrayList<>();
+ for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
+ interiorRings.add(transformCCW(polygon.getInteriorRingN(i), false));
+ }
+
+ return new GeometryFactory(polygon.getPrecisionModel(), polygon.getSRID())
+ .createPolygon(exteriorRingEnforced, interiorRings.toArray(new LinearRing[0]));
+ }
+
+ private static LinearRing transformCCW(LinearRing ring, boolean isExteriorRing) {
+ boolean isRingCounterClockwise = Orientation.isCCW(ring.getCoordinateSequence());
+
+ LinearRing enforcedRing;
+ if (isExteriorRing) {
+ enforcedRing = isRingCounterClockwise ? (LinearRing) ring.copy() : ring.reverse();
+ } else {
+ enforcedRing = isRingCounterClockwise ? ring.reverse() : (LinearRing) ring.copy();
+ }
+ return enforcedRing;
+ }
+
+ /**
+ * This function accepts Polygon and MultiPolygon, if any other type is provided then it will
+ * return false. If the exterior ring is counter-clockwise and the interior ring(s) are clockwise
+ * then returns true, otherwise false.
+ *
+ * @param geom Polygon or MultiPolygon
+ * @return
+ */
+ public static boolean isPolygonCCW(Geometry geom) {
+ if (geom instanceof MultiPolygon) {
+ MultiPolygon multiPolygon = (MultiPolygon) geom;
+
+ boolean arePolygonsCCW = checkIfPolygonCCW(((Polygon) multiPolygon.getGeometryN(0)));
+ for (int i = 1; i < multiPolygon.getNumGeometries(); i++) {
+ arePolygonsCCW =
+ arePolygonsCCW && checkIfPolygonCCW((Polygon) multiPolygon.getGeometryN(i));
+ }
+ return arePolygonsCCW;
+ } else if (geom instanceof Polygon) {
+ return checkIfPolygonCCW((Polygon) geom);
+ }
+ // False for remaining geometry types
+ return false;
+ }
+
+ private static boolean checkIfPolygonCCW(Polygon geom) {
+ LinearRing exteriorRing = geom.getExteriorRing();
+ boolean isExteriorRingCCW = Orientation.isCCW(exteriorRing.getCoordinateSequence());
+
+ boolean isInteriorRingCCW =
+ !Orientation.isCCW(geom.getInteriorRingN(0).getCoordinateSequence());
+ for (int i = 1; i < geom.getNumInteriorRing(); i++) {
+ isInteriorRingCCW =
+ isInteriorRingCCW && !Orientation.isCCW(geom.getInteriorRingN(i).getCoordinateSequence());
+ }
+
+ return isExteriorRingCCW && isInteriorRingCCW;
+ }
+
+ public static Geometry addMeasure(Geometry geom, double measure_start, double measure_end) {
+ return GeomUtils.addMeasure(geom, measure_start, measure_end);
+ }
+
+ public static double maxDistance(Geometry geom1, Geometry geom2) {
+ return longestLine(geom1, geom2).getLength();
+ }
+
+ public static Geometry longestLine(Geometry geom1, Geometry geom2) {
+ double maxLength = -Double.MAX_VALUE;
+ Coordinate longestStart = null;
+ Coordinate longestEnd = null;
+
+ for (Coordinate coord1 : geom1.getCoordinates()) {
+ for (Coordinate coord2 : geom2.getCoordinates()) {
+ double length = coord1.distance(coord2);
+ if (length > maxLength) {
+ maxLength = length;
+ longestStart = coord1;
+ longestEnd = coord2;
+ }
+ }
+ }
+ return geom1.getFactory().createLineString(new Coordinate[] {longestStart, longestEnd});
+ }
+
+ public static Geometry difference(Geometry leftGeometry, Geometry rightGeometry) {
+ boolean isIntersects = leftGeometry.intersects(rightGeometry);
+ if (!isIntersects) {
+ return leftGeometry;
+ } else if (rightGeometry.contains(leftGeometry)) {
+ return EMPTY_POLYGON;
+ } else {
+ return leftGeometry.difference(rightGeometry);
+ }
+ }
+
+ public static Geometry split(Geometry input, Geometry blade) {
+ // check input geometry
+ return new GeometrySplitter(GEOMETRY_FACTORY).split(input, blade);
+ }
+
+ public static Integer dimension(Geometry geometry) {
+ Integer dimension = geometry.getDimension();
+ // unknown dimension such as an empty GEOMETRYCOLLECTION
+ if (dimension < 0) {
+ dimension = 0;
+ }
+ return dimension;
+ }
+
+ /**
+ * get the coordinates of a geometry and transform to Google s2 cell id
+ *
+ * @param input Geometry
+ * @param level integer, minimum level of cells covering the geometry
+ * @return List of coordinates
+ */
+ public static Long[] s2CellIDs(Geometry input, int level) {
+ HashSet<S2CellId> cellIds = new HashSet<>();
+ List<Geometry> geoms = GeomUtils.extractGeometryCollection(input);
+ for (Geometry geom : geoms) {
+ try {
+ cellIds.addAll(
+ S2Utils.s2RegionToCellIDs(S2Utils.toS2Region(geom), 1, level, Integer.MAX_VALUE - 1));
+ } catch (IllegalArgumentException e) {
+ // the geometry can't be cast to region, we cover its coordinates, for example, Point
+ cellIds.addAll(
+ Arrays.stream(geom.getCoordinates())
+ .map(c -> S2Utils.coordinateToCellID(c, level))
+ .collect(Collectors.toList()));
+ }
+ }
+ return S2Utils.roundCellsToSameLevel(new ArrayList<>(cellIds), level).stream()
+ .map(S2CellId::id)
+ .collect(Collectors.toList())
+ .toArray(new Long[cellIds.size()]);
+ }
+
+ /**
+ * @param cellIds array of cell ids
+ * @return An array of polygons for the cell ids
+ */
+ public static Geometry[] s2ToGeom(long[] cellIds) {
+ List<S2CellId> s2CellObjs =
+ Arrays.stream(cellIds).mapToObj(S2CellId::new).collect(Collectors.toList());
+ return s2CellObjs.stream().map(S2Utils::toJTSPolygon).toArray(Polygon[]::new);
+ }
+
+ /**
+ * cover the geometry with H3 cells
+ *
+ * @param input the input geometry
+ * @param level the resolution of h3 cells
+ * @param fullCover whether enforce full cover or not.
+ * @return
+ */
+ public static Long[] h3CellIDs(Geometry input, int level, boolean fullCover) {
+ if (level < 0 || level > 15) {
+ throw new IllegalArgumentException("level must be between 0 and 15");
+ }
+ HashSet<Long> cellIds = new HashSet<>();
+ // first flat all GeometryCollection implementations into single Geometry types (Polygon,
+ // LineString, Point)
+ List<Geometry> geoms = GeomUtils.extractGeometryCollection(input);
+ for (Geometry geom : geoms) {
+ if (geom instanceof Polygon) {
+ cellIds.addAll(H3Utils.polygonToCells((Polygon) geom, level, fullCover));
+ } else if (geom instanceof LineString) {
+ cellIds.addAll(H3Utils.lineStringToCells((LineString) geom, level, fullCover));
+ } else if (geom instanceof Point) {
+ cellIds.add(H3Utils.coordinateToCell(geom.getCoordinate(), level));
+ } else {
+ // if not type of polygon, point or lienSting, we cover its MBR
+ cellIds.addAll(H3Utils.polygonToCells((Polygon) geom.getEnvelope(), level, fullCover));
+ }
+ }
+ return cellIds.toArray(new Long[0]);
+ }
+
+ /**
+ * return the distance between 2 cells, if the native h3 function doesn't work, use our
+ * approximation function for shortest path and use the size - 1 as distance
+ *
+ * @param cell1 source cell
+ * @param cell2 destination cell
+ * @return
+ */
+ public static long h3CellDistance(long cell1, long cell2) {
+ int resolution = H3Utils.h3.getResolution(cell1);
+ if (resolution != H3Utils.h3.getResolution(cell2)) {
+ throw new IllegalArgumentException("The argument cells should be of the same resolution");
+ }
+ try {
+ return H3Utils.h3.gridDistance(cell1, cell2);
+ } catch (H3Exception e) {
+ // approximate if the original function hit error
+ return H3Utils.approxPathCells(
+ H3Utils.cellToCoordinate(cell1),
+ H3Utils.cellToCoordinate(cell2),
+ resolution,
+ true)
+ .size()
+ - 1;
+ }
+ }
+
+ /**
+ * get the neighbor cells of the input cell by h3.gridDisk function
+ *
+ * @param cell: original cell
+ * @param k: the k number of rings spread from the original cell
+ * @param exactDistance: if exactDistance is true, it will only return the cells on the exact kth
+ * ring, else will return all 0 - kth neighbors
+ * @return
+ */
+ public static Long[] h3KRing(long cell, int k, boolean exactDistance) {
+ Set<Long> cells = new LinkedHashSet<>(H3Utils.h3.gridDisk(cell, k));
+ if (exactDistance && k > 0) {
+ List<Long> tbdCells = H3Utils.h3.gridDisk(cell, k - 1);
+ tbdCells.forEach(cells::remove);
+ }
+ return cells.toArray(new Long[0]);
+ }
+
+ /**
+ * gets the polygon for each h3 index provided
+ *
+ * @param cells: the set of cells
+ * @return An Array of Polygons reversed
+ */
+ public static Geometry[] h3ToGeom(long[] cells) {
+ GeometryFactory geomFactory = new GeometryFactory();
+ List<Long> h3 = Arrays.stream(cells).boxed().collect(Collectors.toList());
+ List<Polygon> polygons = new ArrayList<>();
+
+ for (int j = 0; j < h3.size(); j++) {
+ for (List<List<LatLng>> shellHoles :
+ H3Utils.h3.cellsToMultiPolygon(Collections.singleton(h3.get(j)), true)) {
+ List<LinearRing> rings = new ArrayList<>();
+ for (List<LatLng> shell : shellHoles) {
+ Coordinate[] coordinates = new Coordinate[shell.size()];
+ for (int i = 0; i < shell.size(); i++) {
+ LatLng latLng = shell.get(i);
+ coordinates[i] = new Coordinate(latLng.lng, latLng.lat);
+ }
+ LinearRing ring = geomFactory.createLinearRing(coordinates);
+ rings.add(ring);
+ }
+
+ LinearRing shell = rings.remove(0);
+ if (rings.isEmpty()) {
+ polygons.add(geomFactory.createPolygon(shell));
} else {
- circle = geometry.getFactory().createPoint(centre);
- if (radius != 0D) {
- circle = circle.buffer(radius, quadrantSegments);
- }
- }
- return circle;
- }
-
- public static Pair<Geometry, Double> minimumBoundingRadius(Geometry geometry) {
- MinimumBoundingCircle minimumBoundingCircle = new MinimumBoundingCircle(geometry);
- Coordinate coods = minimumBoundingCircle.getCentre();
- double radius = minimumBoundingCircle.getRadius();
- Point centre = GEOMETRY_FACTORY.createPoint(coods);
- return Pair.of(centre, radius);
- }
-
- public static double minimumClearance(Geometry geometry) {
- return MinimumClearance.getDistance(geometry);
- }
-
- public static Geometry minimumClearanceLine(Geometry geometry) {
- return MinimumClearance.getLine(geometry);
- }
-
- public static Geometry lineSubString(Geometry geom, double fromFraction, double toFraction) {
- double length = geom.getLength();
- LengthIndexedLine indexedLine = new LengthIndexedLine(geom);
- Geometry subLine = indexedLine.extractLine(length * fromFraction, length * toFraction);
- return subLine;
- }
-
- public static Geometry lineInterpolatePoint(Geometry geom, double fraction) {
- double length = geom.getLength();
- LengthIndexedLine indexedLine = new LengthIndexedLine(geom);
- Coordinate interPoint = indexedLine.extractPoint(length * fraction);
- return GEOMETRY_FACTORY.createPoint(interPoint);
- }
-
- /**
- * Forces a Polygon/MultiPolygon to use clockwise orientation for the exterior ring and a counter-clockwise for the interior ring(s).
- * @param geom
- * @return a clockwise orientated (Multi)Polygon
- */
- public static Geometry forcePolygonCW(Geometry geom) {
- if (isPolygonCW(geom)) {
- return geom;
- }
-
- if (geom instanceof Polygon) {
- return transformCW((Polygon) geom);
-
- } else if (geom instanceof MultiPolygon) {
- List<Polygon> polygons = new ArrayList<>();
- for (int i = 0; i < geom.getNumGeometries(); i++) {
- Polygon polygon = (Polygon) geom.getGeometryN(i);
- polygons.add((Polygon) transformCW(polygon));
- }
-
- return new GeometryFactory().createMultiPolygon(polygons.toArray(new Polygon[0]));
-
- }
- // Non-polygonal geometries are returned unchanged
- return geom;
- }
-
- private static Geometry transformCW(Polygon polygon) {
- LinearRing exteriorRing = polygon.getExteriorRing();
- LinearRing exteriorRingEnforced = transformCW(exteriorRing, true);
-
- List<LinearRing> interiorRings = new ArrayList<>();
- for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
- interiorRings.add(transformCW(polygon.getInteriorRingN(i), false));
- }
-
- return new GeometryFactory(polygon.getPrecisionModel(), polygon.getSRID())
- .createPolygon(exteriorRingEnforced, interiorRings.toArray(new LinearRing[0]));
- }
-
- private static LinearRing transformCW(LinearRing ring, boolean isExteriorRing) {
- boolean isRingClockwise = !Orientation.isCCW(ring.getCoordinateSequence());
-
- LinearRing enforcedRing;
- if (isExteriorRing) {
- enforcedRing = isRingClockwise ? (LinearRing) ring.copy() : ring.reverse();
- } else {
- enforcedRing = isRingClockwise ? ring.reverse() : (LinearRing) ring.copy();
- }
- return enforcedRing;
- }
-
- /**
- * This function accepts Polygon and MultiPolygon, if any other type is provided then it will return false.
- * If the exterior ring is clockwise and the interior ring(s) are counter-clockwise then returns true, otherwise false.
- * @param geom Polygon or MultiPolygon
- * @return
- */
- public static boolean isPolygonCW(Geometry geom) {
- if (geom instanceof MultiPolygon) {
- MultiPolygon multiPolygon = (MultiPolygon) geom;
-
- boolean arePolygonsCW = checkIfPolygonCW((Polygon) multiPolygon.getGeometryN(0));
- for (int i = 1; i < multiPolygon.getNumGeometries(); i++) {
- arePolygonsCW = arePolygonsCW && checkIfPolygonCW((Polygon) multiPolygon.getGeometryN(i));
- }
- return arePolygonsCW;
- } else if (geom instanceof Polygon) {
- return checkIfPolygonCW((Polygon) geom);
- }
- // False for remaining geometry types
- return false;
- }
-
- private static boolean checkIfPolygonCW(Polygon geom) {
- LinearRing exteriorRing = geom.getExteriorRing();
- boolean isExteriorRingCW = !Orientation.isCCW(exteriorRing.getCoordinateSequence());
-
- boolean isInteriorRingCW = Orientation.isCCW(geom.getInteriorRingN(0).getCoordinateSequence());
- for (int i = 1; i < geom.getNumInteriorRing(); i++) {
- isInteriorRingCW = isInteriorRingCW && Orientation.isCCW(geom.getInteriorRingN(i).getCoordinateSequence());
- }
-
- return isExteriorRingCW && isInteriorRingCW;
- }
-
- public static Geometry triangulatePolygon(Geometry geom) {
- return ConstrainedDelaunayTriangulator.triangulate(geom);
- }
-
- public static double lineLocatePoint(Geometry geom, Geometry point)
- {
- double length = geom.getLength();
- LengthIndexedLine indexedLine = new LengthIndexedLine(geom);
- return indexedLine.indexOf(point.getCoordinate()) / length;
- }
-
- public static Geometry locateAlong(Geometry linear, double measure, double offset) {
- return GeometryLocateAlongProcessor.processGeometry(linear, measure, offset);
- }
-
- public static Geometry locateAlong(Geometry linear, double measure) {
- return locateAlong(linear, measure, 0);
- }
-
- /**
- * Forces a Polygon/MultiPolygon to use counter-clockwise orientation for the exterior ring and a clockwise for the interior ring(s).
- * @param geom
- * @return a counter-clockwise orientated (Multi)Polygon
- */
- public static Geometry forcePolygonCCW(Geometry geom) {
- if (isPolygonCCW(geom)) {
- return geom;
- }
-
- if (geom instanceof Polygon) {
- return transformCCW((Polygon) geom);
-
- } else if (geom instanceof MultiPolygon) {
- List<Polygon> polygons = new ArrayList<>();
- for (int i = 0; i < geom.getNumGeometries(); i++) {
- Polygon polygon = (Polygon) geom.getGeometryN(i);
- polygons.add((Polygon) transformCCW(polygon));
- }
-
- return new GeometryFactory().createMultiPolygon(polygons.toArray(new Polygon[0]));
-
- }
- // Non-polygonal geometries are returned unchanged
- return geom;
- }
-
- private static Geometry transformCCW(Polygon polygon) {
- LinearRing exteriorRing = polygon.getExteriorRing();
- LinearRing exteriorRingEnforced = transformCCW(exteriorRing, true);
-
- List<LinearRing> interiorRings = new ArrayList<>();
- for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
- interiorRings.add(transformCCW(polygon.getInteriorRingN(i), false));
- }
-
- return new GeometryFactory(polygon.getPrecisionModel(), polygon.getSRID())
- .createPolygon(exteriorRingEnforced, interiorRings.toArray(new LinearRing[0]));
- }
-
- private static LinearRing transformCCW(LinearRing ring, boolean isExteriorRing) {
- boolean isRingCounterClockwise = Orientation.isCCW(ring.getCoordinateSequence());
-
- LinearRing enforcedRing;
- if (isExteriorRing) {
- enforcedRing = isRingCounterClockwise ? (LinearRing) ring.copy() : ring.reverse();
- } else {
- enforcedRing = isRingCounterClockwise ? ring.reverse() : (LinearRing) ring.copy();
- }
- return enforcedRing;
- }
-
- /**
- * This function accepts Polygon and MultiPolygon, if any other type is provided then it will return false.
- * If the exterior ring is counter-clockwise and the interior ring(s) are clockwise then returns true, otherwise false.
- * @param geom Polygon or MultiPolygon
- * @return
- */
- public static boolean isPolygonCCW(Geometry geom) {
- if (geom instanceof MultiPolygon) {
- MultiPolygon multiPolygon = (MultiPolygon) geom;
-
- boolean arePolygonsCCW = checkIfPolygonCCW(((Polygon) multiPolygon.getGeometryN(0)));
- for (int i = 1; i < multiPolygon.getNumGeometries(); i++) {
- arePolygonsCCW = arePolygonsCCW && checkIfPolygonCCW((Polygon) multiPolygon.getGeometryN(i));
- }
- return arePolygonsCCW;
- } else if (geom instanceof Polygon) {
- return checkIfPolygonCCW((Polygon) geom);
- }
- // False for remaining geometry types
- return false;
- }
-
- private static boolean checkIfPolygonCCW(Polygon geom) {
- LinearRing exteriorRing = geom.getExteriorRing();
- boolean isExteriorRingCCW = Orientation.isCCW(exteriorRing.getCoordinateSequence());
-
- boolean isInteriorRingCCW = !Orientation.isCCW(geom.getInteriorRingN(0).getCoordinateSequence());
- for (int i = 1; i < geom.getNumInteriorRing(); i++) {
- isInteriorRingCCW = isInteriorRingCCW && !Orientation.isCCW(geom.getInteriorRingN(i).getCoordinateSequence());
- }
-
- return isExteriorRingCCW && isInteriorRingCCW;
- }
-
- public static Geometry addMeasure(Geometry geom, double measure_start, double measure_end) {
- return GeomUtils.addMeasure(geom, measure_start, measure_end);
- }
-
- public static double maxDistance(Geometry geom1, Geometry geom2) {
- return longestLine(geom1, geom2).getLength();
- }
-
- public static Geometry longestLine(Geometry geom1, Geometry geom2) {
- double maxLength = - Double.MAX_VALUE;
- Coordinate longestStart = null;
- Coordinate longestEnd = null;
-
- for (Coordinate coord1: geom1.getCoordinates()) {
- for (Coordinate coord2: geom2.getCoordinates()) {
- double length = coord1.distance(coord2);
- if (length > maxLength) {
- maxLength = length;
- longestStart = coord1;
- longestEnd = coord2;
- }
- }
- }
- return geom1.getFactory().createLineString(new Coordinate[] {longestStart, longestEnd});
- }
-
- public static Geometry difference(Geometry leftGeometry, Geometry rightGeometry) {
- boolean isIntersects = leftGeometry.intersects(rightGeometry);
- if (!isIntersects) {
- return leftGeometry;
- } else if (rightGeometry.contains(leftGeometry)) {
- return EMPTY_POLYGON;
- } else {
- return leftGeometry.difference(rightGeometry);
- }
- }
-
- public static Geometry split(Geometry input, Geometry blade) {
- // check input geometry
- return new GeometrySplitter(GEOMETRY_FACTORY).split(input, blade);
- }
-
- public static Integer dimension(Geometry geometry) {
- Integer dimension = geometry.getDimension();
- // unknown dimension such as an empty GEOMETRYCOLLECTION
- if (dimension < 0) {
- dimension = 0;
- }
- return dimension;
- }
-
- /**
- * get the coordinates of a geometry and transform to Google s2 cell id
- * @param input Geometry
- * @param level integer, minimum level of cells covering the geometry
- * @return List of coordinates
- */
- public static Long[] s2CellIDs(Geometry input, int level) {
- HashSet<S2CellId> cellIds = new HashSet<>();
- List<Geometry> geoms = GeomUtils.extractGeometryCollection(input);
- for (Geometry geom : geoms) {
- try {
- cellIds.addAll(S2Utils.s2RegionToCellIDs(S2Utils.toS2Region(geom), 1, level, Integer.MAX_VALUE - 1));
- } catch (IllegalArgumentException e) {
- // the geometry can't be cast to region, we cover its coordinates, for example, Point
- cellIds.addAll(Arrays.stream(geom.getCoordinates()).map(c -> S2Utils.coordinateToCellID(c, level)).collect(Collectors.toList()));
- }
- }
- return S2Utils.roundCellsToSameLevel(new ArrayList<>(cellIds), level).stream().map(S2CellId::id).collect(Collectors.toList()).toArray(new Long[cellIds.size()]);
- }
-
- /**
- *
- * @param cellIds array of cell ids
- * @return An array of polygons for the cell ids
- */
- public static Geometry[] s2ToGeom(long[] cellIds) {
- List<S2CellId> s2CellObjs = Arrays.stream(cellIds).mapToObj(S2CellId::new).collect(Collectors.toList());
- return s2CellObjs.stream().map(S2Utils::toJTSPolygon).toArray(Polygon[]::new);
- }
-
- /**
- * cover the geometry with H3 cells
- * @param input the input geometry
- * @param level the resolution of h3 cells
- * @param fullCover whether enforce full cover or not.
- * @return
- */
- public static Long[] h3CellIDs(Geometry input, int level, boolean fullCover) {
- if (level < 0 || level > 15) {
- throw new IllegalArgumentException("level must be between 0 and 15");
- }
- HashSet<Long> cellIds = new HashSet<>();
- // first flat all GeometryCollection implementations into single Geometry types (Polygon, LineString, Point)
- List<Geometry> geoms = GeomUtils.extractGeometryCollection(input);
- for (Geometry geom : geoms) {
- if (geom instanceof Polygon) {
- cellIds.addAll(H3Utils.polygonToCells((Polygon) geom, level, fullCover));
- } else if (geom instanceof LineString) {
- cellIds.addAll(H3Utils.lineStringToCells((LineString) geom, level, fullCover));
- } else if (geom instanceof Point){
- cellIds.add(H3Utils.coordinateToCell(geom.getCoordinate(), level));
- } else {
- // if not type of polygon, point or lienSting, we cover its MBR
- cellIds.addAll(H3Utils.polygonToCells((Polygon)geom.getEnvelope(), level, fullCover));
- }
- }
- return cellIds.toArray(new Long[0]);
- }
-
- /**
- * return the distance between 2 cells, if the native h3 function doesn't work, use our approximation function for shortest path and use the size - 1 as distance
- * @param cell1 source cell
- * @param cell2 destination cell
- * @return
- */
- public static long h3CellDistance(long cell1, long cell2) {
- int resolution = H3Utils.h3.getResolution(cell1);
- if (resolution != H3Utils.h3.getResolution(cell2)) {
- throw new IllegalArgumentException("The argument cells should be of the same resolution");
- }
- try {
- return H3Utils.h3.gridDistance(cell1, cell2);
- } catch (H3Exception e) {
- // approximate if the original function hit error
- return H3Utils.approxPathCells(
- H3Utils.cellToCoordinate(cell1),
- H3Utils.cellToCoordinate(cell2),
- resolution,
- true
- ).size() - 1;
- }
- }
-
- /**
- * get the neighbor cells of the input cell by h3.gridDisk function
- * @param cell: original cell
- * @param k: the k number of rings spread from the original cell
- * @param exactDistance: if exactDistance is true, it will only return the cells on the exact kth ring, else will return all 0 - kth neighbors
- * @return
- */
- public static Long[] h3KRing(long cell, int k, boolean exactDistance) {
- Set<Long> cells = new LinkedHashSet<>(H3Utils.h3.gridDisk(cell, k));
- if (exactDistance && k > 0) {
- List<Long> tbdCells = H3Utils.h3.gridDisk(cell, k - 1);
- tbdCells.forEach(cells::remove);
- }
- return cells.toArray(new Long[0]);
- }
-
- /**
- * gets the polygon for each h3 index provided
- * @param cells: the set of cells
- * @return An Array of Polygons reversed
- */
- public static Geometry[] h3ToGeom(long[] cells) {
- GeometryFactory geomFactory = new GeometryFactory();
- List<Long> h3 = Arrays.stream(cells).boxed().collect(Collectors.toList());
- List<Polygon> polygons = new ArrayList<>();
-
- for (int j = 0; j < h3.size(); j++) {
- for (List<List<LatLng>> shellHoles : H3Utils.h3.cellsToMultiPolygon(Collections.singleton(h3.get(j)), true)) {
- List<LinearRing> rings = new ArrayList<>();
- for (List<LatLng> shell : shellHoles) {
- Coordinate[] coordinates = new Coordinate[shell.size()];
- for (int i = 0; i < shell.size(); i++) {
- LatLng latLng = shell.get(i);
- coordinates[i] = new Coordinate(latLng.lng, latLng.lat);
- }
- LinearRing ring = geomFactory.createLinearRing(coordinates);
- rings.add(ring);
- }
-
- LinearRing shell = rings.remove(0);
- if (rings.isEmpty()) {
- polygons.add(geomFactory.createPolygon(shell));
- } else {
- polygons.add(geomFactory.createPolygon(shell, rings.toArray(new LinearRing[0])));
- }
- }
- }
- return polygons.toArray(new Polygon[0]);
- }
-
- // create static function named simplifyPreserveTopology
- public static Geometry simplifyPreserveTopology(Geometry geometry, double distanceTolerance) {
- return TopologyPreservingSimplifier.simplify(geometry, distanceTolerance);
- }
-
- public static Geometry simplifyVW(Geometry geometry, double tolerance) {
- // JTS squares the tolerance in its implementation, inorder to keep it consistent square rooting the input tolerance
- // source: https://github.com/locationtech/jts/blob/7ef2b9d2e6f36ce5e7a787cff57bd18281e50826/modules/core/src/main/java/org/locationtech/jts/simplify/VWLineSimplifier.java#L41
- tolerance = Math.sqrt(tolerance);
- return VWSimplifier.simplify(geometry, tolerance);
- }
-
- public static Geometry simplifyPolygonHull(Geometry geometry, double vertexFactor, boolean isOuter) {
- return PolygonHullSimplifier.hull(geometry, isOuter, vertexFactor);
- }
-
- public static Geometry simplifyPolygonHull(Geometry geometry, double vertexFactor) {
- return simplifyPolygonHull(geometry, vertexFactor, true);
- }
-
- public static String geometryType(Geometry geometry) {
- return "ST_" + geometry.getGeometryType();
- }
-
- public static String geometryTypeWithMeasured(Geometry geometry) {
- String geometryType = geometry.getGeometryType().toUpperCase();
- if (GeomUtils.isMeasuredGeometry(geometry)) {
- geometryType += "M";
- }
- return geometryType;
- }
-
- public static Geometry startPoint(Geometry geometry) {
- if (geometry instanceof LineString) {
- LineString line = (LineString) geometry;
- return line.getStartPoint();
- }
- return null;
- }
-
- public static Geometry endPoint(Geometry geometry) {
- if (geometry instanceof LineString) {
- LineString line = (LineString) geometry;
- return line.getEndPoint();
- }
- return null;
- }
-
- public static Geometry[] dump(Geometry geometry) {
- int numGeom = geometry.getNumGeometries();
- if (geometry instanceof GeometryCollection) {
- Geometry[] geoms = new Geometry[geometry.getNumGeometries()];
- for (int i = 0; i < numGeom; i++) {
- geoms[i] = geometry.getGeometryN(i);
- }
- return geoms;
- } else {
- return new Geometry[] {geometry};
- }
- }
-
- public static Geometry[] dumpPoints(Geometry geometry) {
- return Arrays.stream(geometry.getCoordinates()).map(GEOMETRY_FACTORY::createPoint).toArray(Point[]::new);
- }
-
- public static Geometry symDifference(Geometry leftGeom, Geometry rightGeom) {
- return leftGeom.symDifference(rightGeom);
- }
-
- public static Geometry union(Geometry leftGeom, Geometry rightGeom) {
- return leftGeom.union(rightGeom);
- }
-
- public static Geometry union(Geometry[] geoms) {
- return GEOMETRY_FACTORY.createGeometryCollection(geoms).union();
- }
-
- public static Geometry unaryUnion(Geometry geom) {
- return UnaryUnionOp.union(geom);
- }
-
- public static Geometry createMultiGeometryFromOneElement(Geometry geometry) {
- if (geometry instanceof Circle) {
- return GEOMETRY_FACTORY.createGeometryCollection(new Circle[] {(Circle) geometry});
- } else if (geometry instanceof GeometryCollection) {
- return geometry;
- } else if (geometry instanceof LineString) {
- return GEOMETRY_FACTORY.createMultiLineString(new LineString[]{(LineString) geometry});
- } else if (geometry instanceof Point) {
- return GEOMETRY_FACTORY.createMultiPoint(new Point[] {(Point) geometry});
- } else if (geometry instanceof Polygon) {
- return GEOMETRY_FACTORY.createMultiPolygon(new Polygon[] {(Polygon) geometry});
- } else {
- return GEOMETRY_FACTORY.createGeometryCollection();
- }
- }
-
- public static Geometry[] subDivide(Geometry geometry, int maxVertices) {
- return GeometrySubDivider.subDivide(geometry, maxVertices);
- }
-
- public static Geometry snap(Geometry input, Geometry reference, double tolerance) {
- GeometrySnapper snapper = new GeometrySnapper(input);
- return snapper.snapTo(reference, tolerance);
- }
-
- public static Geometry makeLine(Geometry geom1, Geometry geom2) {
- Geometry[] geoms = new Geometry[]{geom1, geom2};
- return makeLine(geoms);
- }
-
- public static Geometry makeLine(Geometry[] geoms) {
- ArrayList<Coordinate> coordinates = new ArrayList<>();
- for (Geometry geom : geoms) {
- if (geom instanceof Point || geom instanceof MultiPoint || geom instanceof LineString) {
- for (Coordinate coord : geom.getCoordinates()) {
- coordinates.add(coord);
- }
- }
- else {
- throw new IllegalArgumentException("ST_MakeLine only supports Point, MultiPoint and LineString geometries");
- }
- }
-
- Coordinate[] coords = coordinates.toArray(new Coordinate[0]);
- return GEOMETRY_FACTORY.createLineString(coords);
- }
-
- public static Geometry makePolygon(Geometry shell, Geometry[] holes) {
- try {
- if (holes != null) {
- LinearRing[] interiorRings = Arrays.stream(holes).filter(
- h -> h != null && !h.isEmpty() && h instanceof LineString && ((LineString) h).isClosed()
- ).map(
- h -> GEOMETRY_FACTORY.createLinearRing(h.getCoordinates())
- ).toArray(LinearRing[]::new);
- if (interiorRings.length != 0) {
- return GEOMETRY_FACTORY.createPolygon(
- GEOMETRY_FACTORY.createLinearRing(shell.getCoordinates()),
- Arrays.stream(holes).filter(
- h -> h != null && !h.isEmpty() && h instanceof LineString && ((LineString) h).isClosed()
- ).map(
- h -> GEOMETRY_FACTORY.createLinearRing(h.getCoordinates())
- ).toArray(LinearRing[]::new)
- );
- }
- }
- return GEOMETRY_FACTORY.createPolygon(
- GEOMETRY_FACTORY.createLinearRing(shell.getCoordinates())
- );
- } catch (IllegalArgumentException e) {
- return null;
- }
- }
-
- public static Geometry makepolygonWithSRID(Geometry lineString, Integer srid) {
- Geometry geom = makePolygon(lineString, null);
- if(geom != null) {
- geom.setSRID(srid);
- }
- return geom;
- }
-
- public static Geometry createMultiGeometry(Geometry[] geometries) {
- if (geometries.length > 1){
- return GEOMETRY_FACTORY.buildGeometry(Arrays.asList(geometries));
- }
- else if(geometries.length==1){
- return createMultiGeometryFromOneElement(geometries[0]);
- }
- else{
- return GEOMETRY_FACTORY.createGeometryCollection();
- }
- }
-
- public static Geometry collectionExtract(Geometry geometry, Integer geomType) {
- if (geomType == null) {
- return collectionExtract(geometry);
- }
- Class<? extends Geometry> geomClass;
- GeometryCollection emptyResult;
- switch (geomType) {
- case 1:
- geomClass = Point.class;
- emptyResult = GEOMETRY_FACTORY.createMultiPoint();
- break;
- case 2:
- geomClass = LineString.class;
- emptyResult = GEOMETRY_FACTORY.createMultiLineString();
- break;
- case 3:
- geomClass = Polygon.class;
- emptyResult = GEOMETRY_FACTORY.createMultiPolygon();
- break;
- default:
- throw new IllegalArgumentException("Invalid geometry type");
- }
- List<Geometry> geometries = GeomUtils.extractGeometryCollection(geometry, geomClass);
- if (geometries.isEmpty()) {
- return emptyResult;
- }
- return Functions.createMultiGeometry(geometries.toArray(new Geometry[0]));
- }
-
- public static Geometry collectionExtract(Geometry geometry) {
- List<Geometry> geometries = GeomUtils.extractGeometryCollection(geometry);
- Polygon[] polygons = geometries.stream().filter(g -> g instanceof Polygon).toArray(Polygon[]::new);
- if (polygons.length > 0) {
- return GEOMETRY_FACTORY.createMultiPolygon(polygons);
- }
- LineString[] lines = geometries.stream().filter(g -> g instanceof LineString).toArray(LineString[]::new);
- if (lines.length > 0) {
- return GEOMETRY_FACTORY.createMultiLineString(lines);
- }
- Point[] points = geometries.stream().filter(g -> g instanceof Point).toArray(Point[]::new);
- if (points.length > 0) {
- return GEOMETRY_FACTORY.createMultiPoint(points);
- }
- return GEOMETRY_FACTORY.createGeometryCollection();
- }
-
-
- // ported from https://github.com/postgis/postgis/blob/f6ed58d1fdc865d55d348212d02c11a10aeb2b30/liblwgeom/lwgeom_median.c
- // geometry ST_GeometricMedian ( geometry g , float8 tolerance , int max_iter , boolean fail_if_not_converged );
-
- private static double distance3d(Coordinate p1, Coordinate p2) {
- double dx = p2.x - p1.x;
- double dy = p2.y - p1.y;
- double dz = p2.z - p1.z;
- return Math.sqrt(dx * dx + dy * dy + dz * dz);
- }
-
- private static void distances(Coordinate curr, Coordinate[] points, double[] distances) {
- for(int i = 0; i < points.length; i++) {
- distances[i] = distance3d(curr, points[i]);
- }
- }
-
- private static double iteratePoints(Coordinate curr, Coordinate[] points, double[] distances) {
- Coordinate next = new Coordinate(0, 0, 0);
- double delta = 0;
- double denom = 0;
- boolean hit = false;
- distances(curr, points, distances);
-
+ polygons.add(geomFactory.createPolygon(shell, rings.toArray(new LinearRing[0])));
+ }
+ }
+ }
+ return polygons.toArray(new Polygon[0]);
+ }
+
+ // create static function named simplifyPreserveTopology
+ public static Geometry simplifyPreserveTopology(Geometry geometry, double distanceTolerance) {
+ return TopologyPreservingSimplifier.simplify(geometry, distanceTolerance);
+ }
+
+ public static Geometry simplifyVW(Geometry geometry, double tolerance) {
+ // JTS squares the tolerance in its implementation, inorder to keep it consistent square rooting
+ // the input tolerance
+ // source:
+ // https://github.com/locationtech/jts/blob/7ef2b9d2e6f36ce5e7a787cff57bd18281e50826/modules/core/src/main/java/org/locationtech/jts/simplify/VWLineSimplifier.java#L41
+ tolerance = Math.sqrt(tolerance);
+ return VWSimplifier.simplify(geometry, tolerance);
+ }
+
+ public static Geometry simplifyPolygonHull(
+ Geometry geometry, double vertexFactor, boolean isOuter) {
+ return PolygonHullSimplifier.hull(geometry, isOuter, vertexFactor);
+ }
+
+ public static Geometry simplifyPolygonHull(Geometry geometry, double vertexFactor) {
+ return simplifyPolygonHull(geometry, vertexFactor, true);
+ }
+
+ public static String geometryType(Geometry geometry) {
+ return "ST_" + geometry.getGeometryType();
+ }
+
+ public static String geometryTypeWithMeasured(Geometry geometry) {
+ String geometryType = geometry.getGeometryType().toUpperCase();
+ if (GeomUtils.isMeasuredGeometry(geometry)) {
+ geometryType += "M";
+ }
+ return geometryType;
+ }
+
+ public static Geometry startPoint(Geometry geometry) {
+ if (geometry instanceof LineString) {
+ LineString line = (LineString) geometry;
+ return line.getStartPoint();
+ }
+ return null;
+ }
+
+ public static Geometry endPoint(Geometry geometry) {
+ if (geometry instanceof LineString) {
+ LineString line = (LineString) geometry;
+ return line.getEndPoint();
+ }
+ return null;
+ }
+
+ public static Geometry[] dump(Geometry geometry) {
+ int numGeom = geometry.getNumGeometries();
+ if (geometry instanceof GeometryCollection) {
+ Geometry[] geoms = new Geometry[geometry.getNumGeometries()];
+ for (int i = 0; i < numGeom; i++) {
+ geoms[i] = geometry.getGeometryN(i);
+ }
+ return geoms;
+ } else {
+ return new Geometry[] {geometry};
+ }
+ }
+
+ public static Geometry[] dumpPoints(Geometry geometry) {
+ return Arrays.stream(geometry.getCoordinates())
+ .map(GEOMETRY_FACTORY::createPoint)
+ .toArray(Point[]::new);
+ }
+
+ public static Geometry symDifference(Geometry leftGeom, Geometry rightGeom) {
+ return leftGeom.symDifference(rightGeom);
+ }
+
+ public static Geometry union(Geometry leftGeom, Geometry rightGeom) {
+ return leftGeom.union(rightGeom);
+ }
+
+ public static Geometry union(Geometry[] geoms) {
+ return GEOMETRY_FACTORY.createGeometryCollection(geoms).union();
+ }
+
+ public static Geometry unaryUnion(Geometry geom) {
+ return UnaryUnionOp.union(geom);
+ }
+
+ public static Geometry createMultiGeometryFromOneElement(Geometry geometry) {
+ if (geometry instanceof Circle) {
+ return GEOMETRY_FACTORY.createGeometryCollection(new Circle[] {(Circle) geometry});
+ } else if (geometry instanceof GeometryCollection) {
+ return geometry;
+ } else if (geometry instanceof LineString) {
+ return GEOMETRY_FACTORY.createMultiLineString(new LineString[] {(LineString) geometry});
+ } else if (geometry instanceof Point) {
+ return GEOMETRY_FACTORY.createMultiPoint(new Point[] {(Point) geometry});
+ } else if (geometry instanceof Polygon) {
+ return GEOMETRY_FACTORY.createMultiPolygon(new Polygon[] {(Polygon) geometry});
+ } else {
+ return GEOMETRY_FACTORY.createGeometryCollection();
+ }
+ }
+
+ public static Geometry[] subDivide(Geometry geometry, int maxVertices) {
+ return GeometrySubDivider.subDivide(geometry, maxVertices);
+ }
+
+ public static Geometry snap(Geometry input, Geometry reference, double tolerance) {
+ GeometrySnapper snapper = new GeometrySnapper(input);
+ return snapper.snapTo(reference, tolerance);
+ }
+
+ public static Geometry makeLine(Geometry geom1, Geometry geom2) {
+ Geometry[] geoms = new Geometry[] {geom1, geom2};
+ return makeLine(geoms);
+ }
+
+ public static Geometry makeLine(Geometry[] geoms) {
+ ArrayList<Coordinate> coordinates = new ArrayList<>();
+ for (Geometry geom : geoms) {
+ if (geom instanceof Point || geom instanceof MultiPoint || geom instanceof LineString) {
+ for (Coordinate coord : geom.getCoordinates()) {
+ coordinates.add(coord);
+ }
+ } else {
+ throw new IllegalArgumentException(
+ "ST_MakeLine only supports Point, MultiPoint and LineString geometries");
+ }
+ }
+
+ Coordinate[] coords = coordinates.toArray(new Coordinate[0]);
+ return GEOMETRY_FACTORY.createLineString(coords);
+ }
+
+ public static Geometry makePolygon(Geometry shell, Geometry[] holes) {
+ try {
+ if (holes != null) {
+ LinearRing[] interiorRings =
+ Arrays.stream(holes)
+ .filter(
+ h ->
+ h != null
+ && !h.isEmpty()
+ && h instanceof LineString
+ && ((LineString) h).isClosed())
+ .map(h -> GEOMETRY_FACTORY.createLinearRing(h.getCoordinates()))
+ .toArray(LinearRing[]::new);
+ if (interiorRings.length != 0) {
+ return GEOMETRY_FACTORY.createPolygon(
+ GEOMETRY_FACTORY.createLinearRing(shell.getCoordinates()),
+ Arrays.stream(holes)
+ .filter(
+ h ->
+ h != null
+ && !h.isEmpty()
+ && h instanceof LineString
+ && ((LineString) h).isClosed())
+ .map(h -> GEOMETRY_FACTORY.createLinearRing(h.getCoordinates()))
+ .toArray(LinearRing[]::new));
+ }
+ }
+ return GEOMETRY_FACTORY.createPolygon(
+ GEOMETRY_FACTORY.createLinearRing(shell.getCoordinates()));
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ public static Geometry makepolygonWithSRID(Geometry lineString, Integer srid) {
+ Geometry geom = makePolygon(lineString, null);
+ if (geom != null) {
+ geom.setSRID(srid);
+ }
+ return geom;
+ }
+
+ public static Geometry createMultiGeometry(Geometry[] geometries) {
+ if (geometries.length > 1) {
+ return GEOMETRY_FACTORY.buildGeometry(Arrays.asList(geometries));
+ } else if (geometries.length == 1) {
+ return createMultiGeometryFromOneElement(geometries[0]);
+ } else {
+ return GEOMETRY_FACTORY.createGeometryCollection();
+ }
+ }
+
+ public static Geometry collectionExtract(Geometry geometry, Integer geomType) {
+ if (geomType == null) {
+ return collectionExtract(geometry);
+ }
+ Class<? extends Geometry> geomClass;
+ GeometryCollection emptyResult;
+ switch (geomType) {
+ case 1:
+ geomClass = Point.class;
+ emptyResult = GEOMETRY_FACTORY.createMultiPoint();
+ break;
+ case 2:
+ geomClass = LineString.class;
+ emptyResult = GEOMETRY_FACTORY.createMultiLineString();
+ break;
+ case 3:
+ geomClass = Polygon.class;
+ emptyResult = GEOMETRY_FACTORY.createMultiPolygon();
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid geometry type");
+ }
+ List<Geometry> geometries = GeomUtils.extractGeometryCollection(geometry, geomClass);
+ if (geometries.isEmpty()) {
+ return emptyResult;
+ }
+ return Functions.createMultiGeometry(geometries.toArray(new Geometry[0]));
+ }
+
+ public static Geometry collectionExtract(Geometry geometry) {
+ List<Geometry> geometries = GeomUtils.extractGeometryCollection(geometry);
+ Polygon[] polygons =
+ geometries.stream().filter(g -> g instanceof Polygon).toArray(Polygon[]::new);
+ if (polygons.length > 0) {
+ return GEOMETRY_FACTORY.createMultiPolygon(polygons);
+ }
+ LineString[] lines =
+ geometries.stream().filter(g -> g instanceof LineString).toArray(LineString[]::new);
+ if (lines.length > 0) {
+ return GEOMETRY_FACTORY.createMultiLineString(lines);
+ }
+ Point[] points = geometries.stream().filter(g -> g instanceof Point).toArray(Point[]::new);
+ if (points.length > 0) {
+ return GEOMETRY_FACTORY.createMultiPoint(points);
+ }
+ return GEOMETRY_FACTORY.createGeometryCollection();
+ }
+
+ // ported from
+ // https://github.com/postgis/postgis/blob/f6ed58d1fdc865d55d348212d02c11a10aeb2b30/liblwgeom/lwgeom_median.c
+ // geometry ST_GeometricMedian ( geometry g , float8 tolerance , int max_iter , boolean
+ // fail_if_not_converged );
+
+ private static double distance3d(Coordinate p1, Coordinate p2) {
+ double dx = p2.x - p1.x;
+ double dy = p2.y - p1.y;
+ double dz = p2.z - p1.z;
+ return Math.sqrt(dx * dx + dy * dy + dz * dz);
+ }
+
+ private static void distances(Coordinate curr, Coordinate[] points, double[] distances) {
+ for (int i = 0; i < points.length; i++) {
+ distances[i] = distance3d(curr, points[i]);
+ }
+ }
+
+ private static double iteratePoints(Coordinate curr, Coordinate[] points, double[] distances) {
+ Coordinate next = new Coordinate(0, 0, 0);
+ double delta = 0;
+ double denom = 0;
+ boolean hit = false;
+ distances(curr, points, distances);
+
+ for (int i = 0; i < points.length; i++) {
+ /* we need to use lower epsilon than in FP_IS_ZERO in the loop for calculation to converge */
+ double distance = distances[i];
+ if (distance > DBL_EPSILON) {
+ Coordinate coordinate = points[i];
+ next.x += coordinate.x / distance;
+ next.y += coordinate.y / distance;
+ next.z += coordinate.z / distance;
+ denom += 1.0 / distance;
+ } else {
+ hit = true;
+ }
+ }
+ /* negative weight shouldn't get here */
+ // assert(denom >= 0);
+
+ /* denom is zero in case of multipoint of single point when we've converged perfectly */
+ if (denom > DBL_EPSILON) {
+ next.x /= denom;
+ next.y /= denom;
+ next.z /= denom;
+
+ /* If any of the intermediate points in the calculation is found in the
+ * set of input points, the standard Weiszfeld method gets stuck with a
+ * divide-by-zero.
+ *
+ * To get ourselves out of the hole, we follow an alternate procedure to
+ * get the next iteration, as described in:
+ *
+ * Vardi, Y. and Zhang, C. (2011) "A modified Weiszfeld algorithm for the
+ * Fermat-Weber location problem." Math. Program., Ser. A 90: 559-566.
+ * DOI 10.1007/s101070100222
+ *
+ * Available online at the time of this writing at
+ * http://www.stat.rutgers.edu/home/cunhui/papers/43.pdf
+ */
+ if (hit) {
+ double dx = 0;
+ double dy = 0;
+ double dz = 0;
for (int i = 0; i < points.length; i++) {
- /* we need to use lower epsilon than in FP_IS_ZERO in the loop for calculation to converge */
- double distance = distances[i];
- if (distance > DBL_EPSILON) {
- Coordinate coordinate = points[i];
- next.x += coordinate.x / distance;
- next.y += coordinate.y / distance;
- next.z += coordinate.z / distance;
- denom += 1.0 / distance;
- } else {
- hit = true;
- }
- }
- /* negative weight shouldn't get here */
- //assert(denom >= 0);
-
- /* denom is zero in case of multipoint of single point when we've converged perfectly */
- if (denom > DBL_EPSILON) {
- next.x /= denom;
- next.y /= denom;
- next.z /= denom;
-
- /* If any of the intermediate points in the calculation is found in the
- * set of input points, the standard Weiszfeld method gets stuck with a
- * divide-by-zero.
- *
- * To get ourselves out of the hole, we follow an alternate procedure to
- * get the next iteration, as described in:
- *
- * Vardi, Y. and Zhang, C. (2011) "A modified Weiszfeld algorithm for the
- * Fermat-Weber location problem." Math. Program., Ser. A 90: 559-566.
- * DOI 10.1007/s101070100222
- *
- * Available online at the time of this writing at
- * http://www.stat.rutgers.edu/home/cunhui/papers/43.pdf
- */
- if (hit) {
- double dx = 0;
- double dy = 0;
- double dz = 0;
- for (int i = 0; i < points.length; i++) {
- double distance = distances[i];
- if (distance > DBL_EPSILON) {
- Coordinate coordinate = points[i];
- dx += (coordinate.x - curr.x) / distance;
- dy += (coordinate.y - curr.y) / distance;
- dz += (coordinate.z - curr.z) / distance;
- }
- }
- double dSqr = Math.sqrt(dx*dx + dy*dy + dz*dz);
- /* Avoid division by zero if the intermediate point is the median */
- if (dSqr > DBL_EPSILON) {
- double rInv = Math.max(0, 1.0 / dSqr);
- next.x = (1.0 - rInv)*next.x + rInv*curr.x;
- next.y = (1.0 - rInv)*next.y + rInv*curr.y;
- next.z = (1.0 - rInv)*next.z + rInv*curr.z;
- }
- }
- delta = distance3d(curr, next);
- curr.x = next.x;
- curr.y = next.y;
- curr.z = next.z;
- }
- return delta;
- }
-
- private static Coordinate initGuess(Coordinate[] points) {
- Coordinate guess = new Coordinate(0, 0, 0);
- for (Coordinate point : points) {
- guess.x += point.x / points.length;
- guess.y += point.y / points.length;
- guess.z += point.z / points.length;
- }
- return guess;
- }
-
- private static Coordinate[] extractCoordinates(Geometry geometry) {
- Coordinate[] points = geometry.getCoordinates();
- if(points.length == 0)
- return points;
-
- Coordinate[] coordinates = new Coordinate[points.length];
- for(int i = 0; i < points.length; i++) {
- boolean is3d = !Double.isNaN(points[i].z);
- coordinates[i] = points[i].copy();
- if(!is3d)
- coordinates[i].z = 0.0;
- }
- return coordinates;
- }
-
- public static int numPoints(Geometry geometry) throws Exception {
- String geometryType = geometry.getGeometryType();
- if (!(Geometry.TYPENAME_LINESTRING.equalsIgnoreCase(geometryType))) {
- throw new IllegalArgumentException("Unsupported geometry type: " + geometryType + ", only LineString geometry is supported.");
- }
- return geometry.getNumPoints();
- }
-
- public static Geometry force3DM(Geometry geom, double mValue) {
- return GeometryForce3DMTransformer.transform(geom, mValue);
- }
-
- public static Geometry force3DM(Geometry geom) {
- return force3DM(geom, 0.0);
- }
-
- public static Geometry force4D(Geometry geom, double zValue, double mValue) {
- return GeometryForce4DTransformer.transform(geom, zValue, mValue);
- }
-
- public static Geometry force4D(Geometry geom) {
- return force4D(geom, 0.0, 0.0);
- }
-
- public static Geometry force3D(Geometry geometry, double zValue) {
- return GeomUtils.get3DGeom(geometry, zValue);
- }
-
- public static Geometry force3D(Geometry geometry) {
- return GeomUtils.get3DGeom(geometry, 0.0);
- }
-
- public static Geometry forceCollection(Geometry geom) {
- return new GeometryFactory().createGeometryCollection(convertGeometryToArray(geom));
- }
-
- private static Geometry[] convertGeometryToArray(Geometry geom) {
- Geometry[] array = new Geometry[geom.getNumGeometries()];
- for (int i = 0; i < array.length; i++) {
- array[i] = geom.getGeometryN(i);
- }
- return array;
- }
-
- public static Integer nRings(Geometry geometry) throws Exception {
- String geometryType = geometry.getGeometryType();
- if (!(geometry instanceof Polygon || geometry instanceof MultiPolygon)) {
- throw new IllegalArgumentException("Unsupported geometry type: " + geometryType + ", only Polygon or MultiPolygon geometries are supported.");
- }
- int numRings = 0;
- if (geometry instanceof Polygon) {
- Polygon polygon = (Polygon) geometry;
- numRings = GeomUtils.getPolygonNumRings(polygon);
- }else {
- MultiPolygon multiPolygon = (MultiPolygon) geometry;
- int numPolygons = multiPolygon.getNumGeometries();
- for (int i = 0; i < numPolygons; i++) {
- Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
- numRings += GeomUtils.getPolygonNumRings(polygon);
- }
- }
- return numRings;
- }
-
- public static Geometry translate(Geometry geometry, double deltaX, double deltaY, double deltaZ) {
- if (!geometry.isEmpty()) {
- GeomUtils.translateGeom(geometry, deltaX, deltaY, deltaZ);
- }
- return geometry;
- }
-
- public static Geometry translate(Geometry geometry, double deltaX, double deltaY) {
- if (!geometry.isEmpty()) {
- GeomUtils.translateGeom(geometry, deltaX, deltaY, 0.0);
- }
- return geometry;
- }
-
- public static Geometry affine(Geometry geometry, double a, double b, double c, double d, double e, double f, double g, double h, double i, double xOff, double yOff,
- double zOff) {
- if (!geometry.isEmpty()) {
- GeomUtils.affineGeom(geometry, a, b, c, d, e, f, g, h, i, xOff, yOff, zOff);
- }
- return geometry;
- }
-
- public static Geometry affine(Geometry geometry, double a, double b, double d, double e, double xOff, double yOff) {
- if (!geometry.isEmpty()) {
- GeomUtils.affineGeom(geometry, a, b, null, d, e, null, null, null, null, xOff, yOff, null);
- }
- return geometry;
- }
-
- public static Geometry geometricMedian(Geometry geometry, double tolerance, int maxIter, boolean failIfNotConverged) throws Exception {
- String geometryType = geometry.getGeometryType();
- if(!(Geometry.TYPENAME_POINT.equals(geometryType) || Geometry.TYPENAME_MULTIPOINT.equals(geometryType))) {
- throw new Exception("Unsupported geometry type: " + geometryType);
- }
- Coordinate[] coordinates = extractCoordinates(geometry);
- if(coordinates.length == 0)
- return new Point(null, GEOMETRY_FACTORY);
- Coordinate median = initGuess(coordinates);
- double delta = Double.MAX_VALUE;
- double[] distances = new double[coordinates.length]; // preallocate to reduce gc pressure for large iterations
- for(int i = 0; i < maxIter && delta > tolerance; i++)
- delta = iteratePoints(median, coordinates, distances);
- if (failIfNotConverged && delta > tolerance)
- throw new Exception(String.format("Median failed to converge within %.1E after %d iterations.", tolerance, maxIter));
- boolean is3d = !Double.isNaN(geometry.getCoordinate().z);
- if(!is3d)
- median.z = Double.NaN;
- Point point = new Point(new CoordinateArraySequence(new Coordinate[]{median}), GEOMETRY_FACTORY);
- point.setSRID(geometry.getSRID());
- return point;
- }
-
- public static Geometry geometricMedian(Geometry geometry, double tolerance, int maxIter) throws Exception {
- return geometricMedian(geometry, tolerance, maxIter, false);
- }
-
- public static Geometry geometricMedian(Geometry geometry, double tolerance) throws Exception {
- return geometricMedian(geometry, tolerance, DEFAULT_MAX_ITER, false);
- }
-
- public static Geometry geometricMedian(Geometry geometry) throws Exception {
- return geometricMedian(geometry, DEFAULT_TOLERANCE, DEFAULT_MAX_ITER, false);
- }
-
- public static double frechetDistance(Geometry g1, Geometry g2) {
- return GeomUtils.getFrechetDistance(g1, g2);
- }
-
- public static boolean isCollection(Geometry geometry) {
- String geoType = geometry.getGeometryType();
- return Geometry.TYPENAME_GEOMETRYCOLLECTION.equalsIgnoreCase(geoType) ||
- Geometry.TYPENAME_MULTIPOINT.equalsIgnoreCase(geoType) ||
- Geometry.TYPENAME_MULTIPOLYGON.equalsIgnoreCase(geoType) ||
- Geometry.TYPENAME_MULTILINESTRING.equalsIgnoreCase(geoType);
- }
-
- public static Geometry boundingDiagonal(Geometry geometry) {
- if (geometry.isEmpty()) {
- return GEOMETRY_FACTORY.createLineString();
- }else {
- Double startX = null, startY = null, startZ = null,
- endX = null, endY = null, endZ = null;
- boolean is3d = !Double.isNaN(geometry.getCoordinate().z);
- for (Coordinate currCoordinate : geometry.getCoordinates()) {
- startX = startX == null ? currCoordinate.getX() : Math.min(startX, currCoordinate.getX());
- startY = startY == null ? currCoordinate.getY() : Math.min(startY, currCoordinate.getY());
-
- endX = endX == null ? currCoordinate.getX() : Math.max(endX, currCoordinate.getX());
- endY = endY == null ? currCoordinate.getY() : Math.max(endY, currCoordinate.getY());
- if (is3d) {
- Double geomZ = currCoordinate.getZ();
- startZ = startZ == null ? currCoordinate.getZ() : Math.min(startZ, currCoordinate.getZ());
- endZ = endZ == null ? currCoordinate.getZ() : Math.max(endZ, currCoordinate.getZ());
- }
- }
- Coordinate startCoordinate;
- Coordinate endCoordinate;
- if (is3d) {
- startCoordinate = new Coordinate(startX, startY, startZ);
- endCoordinate = new Coordinate(endX, endY, endZ);
- }else {
- startCoordinate = new Coordinate(startX, startY);
- endCoordinate = new Coordinate(endX, endY);
- }
- return GEOMETRY_FACTORY.createLineString(new Coordinate[] {startCoordinate, endCoordinate});
- }
- }
-
- public static double angle(Geometry point1, Geometry point2, Geometry point3, Geometry point4) throws IllegalArgumentException {
- if (point3 == null && point4 == null) return Functions.angle(point1, point2);
- else if (point4 == null) return Functions.angle(point1, point2, point3);
- if (GeomUtils.isAnyGeomEmpty(point1, point2, point3, point4)) throw new IllegalArgumentException("ST_Angle cannot support empty geometries.");
- if (!(point1 instanceof Point && point2 instanceof Point && point3 instanceof Point && point4 instanceof Point)) throw new IllegalArgumentException("ST_Angle supports either only POINT or only LINESTRING geometries.");
- return GeomUtils.calcAngle(point1.getCoordinate(), point2.getCoordinate(), point3.getCoordinate(), point4.getCoordinate());
- }
-
- public static double angle(Geometry point1, Geometry point2, Geometry point3) throws IllegalArgumentException {
- if (GeomUtils.isAnyGeomEmpty(point1, point2, point3)) throw new IllegalArgumentException("ST_Angle cannot support empty geometries.");
- if (!(point1 instanceof Point && point2 instanceof Point && point3 instanceof Point)) throw new IllegalArgumentException("ST_Angle supports either only POINT or only LINESTRING geometries.");
- return GeomUtils.calcAngle(point2.getCoordinate(), point1.getCoordinate(), point2.getCoordinate(), point3.getCoordinate());
- }
-
- public static double angle(Geometry line1, Geometry line2) throws IllegalArgumentException {
- if (GeomUtils.isAnyGeomEmpty(line1, line2)) throw new IllegalArgumentException("ST_Angle cannot support empty geometries.");
- if (!(line1 instanceof LineString && line2 instanceof LineString)) throw new IllegalArgumentException("ST_Angle supports either only POINT or only LINESTRING geometries.");
- Coordinate[] startEndLine1 = GeomUtils.getStartEndCoordinates(line1);
- Coordinate[] startEndLine2 = GeomUtils.getStartEndCoordinates(line2);
- assert startEndLine1 != null;
- assert startEndLine2 != null;
- return GeomUtils.calcAngle(startEndLine1[0], startEndLine1[1], startEndLine2[0], startEndLine2[1]);
- }
-
- public static double degrees(double angleInRadian) {
- return GeomUtils.toDegrees(angleInRadian);
- }
-
- public static Double hausdorffDistance(Geometry g1, Geometry g2, double densityFrac) {
- return GeomUtils.getHausdorffDistance(g1, g2, densityFrac);
- }
-
- public static Double hausdorffDistance(Geometry g1, Geometry g2) {
- return GeomUtils.getHausdorffDistance(g1, g2, -1);
- }
-
- private static IsValidOp getIsValidOpObject(Geometry geom, int flag) {
- IsValidOp isValidOp = new IsValidOp(geom);
-
- // Set the validity model based on flags
- if (flag == ESRI_VALIDITY) {
- isValidOp.setSelfTouchingRingFormingHoleValid(true);
- } else {
- isValidOp.setSelfTouchingRingFormingHoleValid(false);
- }
- return isValidOp;
- }
-
- public static ValidDetail isValidDetail(Geometry geom) {
- return isValidDetail(geom, OGC_SFS_VALIDITY);
- }
-
- public static ValidDetail isValidDetail(Geometry geom, int flag) {
- IsValidOp isValidOp = getIsValidOpObject(geom, flag);
-
- if (isValidOp.isValid()) {
- return new ValidDetail(true, null, null);
- } else {
- TopologyValidationError error = isValidOp.getValidationError();
- String reason = error.toString();
- Geometry location = geom.getFactory().createPoint(error.getCoordinate());
- return new ValidDetail(false, reason, location);
- }
- }
-
- public static String isValidReason(Geometry geom) {
- return isValidReason(geom, OGC_SFS_VALIDITY);
- }
-
- public static String isValidReason(Geometry geom, int flag) {
- IsValidOp isValidOp = getIsValidOpObject(geom, flag);
-
-
- if (isValidOp.isValid()) {
- return "Valid Geometry";
- } else {
- TopologyValidationError error = isValidOp.getValidationError();
- return error.toString();
- }
- }
-
- /**
- * This method takes a GeometryCollection and returns another GeometryCollection
- * containing the polygons formed by the linework of a set of geometries.
- * @param geometry A collection of Geometry objects that should contain only linestrings.
- * @return A GeometryCollection containing the resultant polygons.
- */
- public static Geometry polygonize(Geometry geometry) {
- if (geometry == null || geometry.isEmpty()) {
- return GEOMETRY_FACTORY.createGeometryCollection(null);
- }
-
- if (geometry instanceof GeometryCollection) {
- Polygonizer polygonizer = new Polygonizer();
-
- for (int i = 0; i < geometry.getNumGeometries(); i++) {
- polygonizer.add(geometry.getGeometryN(i));
- }
-
- Collection polygons = polygonizer.getPolygons();
- Geometry[] polyArray = (Geometry[]) polygons.toArray(new Geometry[0]);
-
- return GEOMETRY_FACTORY.createGeometryCollection(polyArray);
- } else {
- return GEOMETRY_FACTORY.createGeometryCollection(null);
- }
- }
-
- /**
- * Creates a MultiPoint containing all coordinates of the given geometry.
- * Duplicates, M and Z coordinates are preserved.
- *
- * @param geometry The input geometry
- * @return A MultiPoint geometry
- */
- public static Geometry points(Geometry geometry) {
- if (geometry == null) {
- return null;
- }
-
- // Extracting all coordinates from the geometry
- Coordinate[] coordinates = geometry.getCoordinates();
-
- // Creating a MultiPoint from the extracted coordinates
- return GEOMETRY_FACTORY.createMultiPointFromCoords(coordinates);
- }
+ double distance = distances[i];
+ if (distance > DBL_EPSILON) {
+ Coordinate coordinate = points[i];
+ dx += (coordinate.x - curr.x) / distance;
+ dy += (coordinate.y - curr.y) / distance;
+ dz += (coordinate.z - curr.z) / distance;
+ }
+ }
+ double dSqr = Math.sqrt(dx * dx + dy * dy + dz * dz);
+ /* Avoid division by zero if the intermediate point is the median */
+ if (dSqr > DBL_EPSILON) {
+ double rInv = Math.max(0, 1.0 / dSqr);
+ next.x = (1.0 - rInv) * next.x + rInv * curr.x;
+ next.y = (1.0 - rInv) * next.y + rInv * curr.y;
+ next.z = (1.0 - rInv) * next.z + rInv * curr.z;
+ }
+ }
+ delta = distance3d(curr, next);
+ curr.x = next.x;
+ curr.y = next.y;
+ curr.z = next.z;
+ }
+ return delta;
+ }
+
+ private static Coordinate initGuess(Coordinate[] points) {
+ Coordinate guess = new Coordinate(0, 0, 0);
+ for (Coordinate point : points) {
+ guess.x += point.x / points.length;
+ guess.y += point.y / points.length;
+ guess.z += point.z / points.length;
+ }
+ return guess;
+ }
+
+ private static Coordinate[] extractCoordinates(Geometry geometry) {
+ Coordinate[] points = geometry.getCoordinates();
+ if (points.length == 0) return points;
+
+ Coordinate[] coordinates = new Coordinate[points.length];
+ for (int i = 0; i < points.length; i++) {
+ boolean is3d = !Double.isNaN(points[i].z);
+ coordinates[i] = points[i].copy();
+ if (!is3d) coordinates[i].z = 0.0;
+ }
+ return coordinates;
+ }
+
+ public static int numPoints(Geometry geometry) throws Exception {
+ String geometryType = geometry.getGeometryType();
+ if (!(Geometry.TYPENAME_LINESTRING.equalsIgnoreCase(geometryType))) {
+ throw new IllegalArgumentException(
+ "Unsupported geometry type: "
+ + geometryType
+ + ", only LineString geometry is supported.");
+ }
+ return geometry.getNumPoints();
+ }
+
+ public static Geometry force3DM(Geometry geom, double mValue) {
+ return GeometryForce3DMTransformer.transform(geom, mValue);
+ }
+
+ public static Geometry force3DM(Geometry geom) {
+ return force3DM(geom, 0.0);
+ }
+
+ public static Geometry force4D(Geometry geom, double zValue, double mValue) {
+ return GeometryForce4DTransformer.transform(geom, zValue, mValue);
+ }
+
+ public static Geometry force4D(Geometry geom) {
+ return force4D(geom, 0.0, 0.0);
+ }
+
+ public static Geometry force3D(Geometry geometry, double zValue) {
+ return GeomUtils.get3DGeom(geometry, zValue);
+ }
+
+ public static Geometry force3D(Geometry geometry) {
+ return GeomUtils.get3DGeom(geometry, 0.0);
+ }
+
+ public static Geometry forceCollection(Geometry geom) {
+ return new GeometryFactory().createGeometryCollection(convertGeometryToArray(geom));
+ }
+
+ private static Geometry[] convertGeometryToArray(Geometry geom) {
+ Geometry[] array = new Geometry[geom.getNumGeometries()];
+ for (int i = 0; i < array.length; i++) {
+ array[i] = geom.getGeometryN(i);
+ }
+ return array;
+ }
+
+ public static Integer nRings(Geometry geometry) throws Exception {
+ String geometryType = geometry.getGeometryType();
+ if (!(geometry instanceof Polygon || geometry instanceof MultiPolygon)) {
+ throw new IllegalArgumentException(
+ "Unsupported geometry type: "
+ + geometryType
+ + ", only Polygon or MultiPolygon geometries are supported.");
+ }
+ int numRings = 0;
+ if (geometry instanceof Polygon) {
+ Polygon polygon = (Polygon) geometry;
+ numRings = GeomUtils.getPolygonNumRings(polygon);
+ } else {
+ MultiPolygon multiPolygon = (MultiPolygon) geometry;
+ int numPolygons = multiPolygon.getNumGeometries();
+ for (int i = 0; i < numPolygons; i++) {
+ Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
+ numRings += GeomUtils.getPolygonNumRings(polygon);
+ }
+ }
+ return numRings;
+ }
+
+ public static Geometry translate(Geometry geometry, double deltaX, double deltaY, double deltaZ) {
+ if (!geometry.isEmpty()) {
+ GeomUtils.translateGeom(geometry, deltaX, deltaY, deltaZ);
+ }
+ return geometry;
+ }
+
+ public static Geometry translate(Geometry geometry, double deltaX, double deltaY) {
+ if (!geometry.isEmpty()) {
+ GeomUtils.translateGeom(geometry, deltaX, deltaY, 0.0);
+ }
+ return geometry;
+ }
+
+ public static Geometry affine(
+ Geometry geometry,
+ double a,
+ double b,
+ double c,
+ double d,
+ double e,
+ double f,
+ double g,
+ double h,
+ double i,
+ double xOff,
+ double yOff,
+ double zOff) {
+ if (!geometry.isEmpty()) {
+ GeomUtils.affineGeom(geometry, a, b, c, d, e, f, g, h, i, xOff, yOff, zOff);
+ }
+ return geometry;
+ }
+
+ public static Geometry affine(
+ Geometry geometry, double a, double b, double d, double e, double xOff, double yOff) {
+ if (!geometry.isEmpty()) {
+ GeomUtils.affineGeom(geometry, a, b, null, d, e, null, null, null, null, xOff, yOff, null);
+ }
+ return geometry;
+ }
+
+ public static Geometry geometricMedian(
+ Geometry geometry, double tolerance, int maxIter, boolean failIfNotConverged)
+ throws Exception {
+ String geometryType = geometry.getGeometryType();
+ if (!(Geometry.TYPENAME_POINT.equals(geometryType)
+ || Geometry.TYPENAME_MULTIPOINT.equals(geometryType))) {
+ throw new Exception("Unsupported geometry type: " + geometryType);
+ }
+ Coordinate[] coordinates = extractCoordinates(geometry);
+ if (coordinates.length == 0) return new Point(null, GEOMETRY_FACTORY);
+ Coordinate median = initGuess(coordinates);
+ double delta = Double.MAX_VALUE;
+ double[] distances =
+ new double[coordinates.length]; // preallocate to reduce gc pressure for large iterations
+ for (int i = 0; i < maxIter && delta > tolerance; i++)
+ delta = iteratePoints(median, coordinates, distances);
+ if (failIfNotConverged && delta > tolerance)
+ throw new Exception(
+ String.format(
+ "Median failed to converge within %.1E after %d iterations.", tolerance, maxIter));
+ boolean is3d = !Double.isNaN(geometry.getCoordinate().z);
+ if (!is3d) median.z = Double.NaN;
+ Point point =
+ new Point(new CoordinateArraySequence(new Coordinate[] {median}), GEOMETRY_FACTORY);
+ point.setSRID(geometry.getSRID());
+ return point;
+ }
+
+ public static Geometry geometricMedian(Geometry geometry, double tolerance, int maxIter)
+ throws Exception {
+ return geometricMedian(geometry, tolerance, maxIter, false);
+ }
+
+ public static Geometry geometricMedian(Geometry geometry, double tolerance) throws Exception {
+ return geometricMedian(geometry, tolerance, DEFAULT_MAX_ITER, false);
+ }
+
+ public static Geometry geometricMedian(Geometry geometry) throws Exception {
+ return geometricMedian(geometry, DEFAULT_TOLERANCE, DEFAULT_MAX_ITER, false);
+ }
+
+ public static double frechetDistance(Geometry g1, Geometry g2) {
+ return GeomUtils.getFrechetDistance(g1, g2);
+ }
+
+ public static boolean isCollection(Geometry geometry) {
+ String geoType = geometry.getGeometryType();
+ return Geometry.TYPENAME_GEOMETRYCOLLECTION.equalsIgnoreCase(geoType)
+ || Geometry.TYPENAME_MULTIPOINT.equalsIgnoreCase(geoType)
+ || Geometry.TYPENAME_MULTIPOLYGON.equalsIgnoreCase(geoType)
+ || Geometry.TYPENAME_MULTILINESTRING.equalsIgnoreCase(geoType);
+ }
+
+ public static Geometry boundingDiagonal(Geometry geometry) {
+ if (geometry.isEmpty()) {
+ return GEOMETRY_FACTORY.createLineString();
+ } else {
+ Double startX = null, startY = null, startZ = null, endX = null, endY = null, endZ = null;
+ boolean is3d = !Double.isNaN(geometry.getCoordinate().z);
+ for (Coordinate currCoordinate : geometry.getCoordinates()) {
+ startX = startX == null ? currCoordinate.getX() : Math.min(startX, currCoordinate.getX());
+ startY = startY == null ? currCoordinate.getY() : Math.min(startY, currCoordinate.getY());
+
+ endX = endX == null ? currCoordinate.getX() : Math.max(endX, currCoordinate.getX());
+ endY = endY == null ? currCoordinate.getY() : Math.max(endY, currCoordinate.getY());
+ if (is3d) {
+ Double geomZ = currCoordinate.getZ();
+ startZ = startZ == null ? currCoordinate.getZ() : Math.min(startZ, currCoordinate.getZ());
+ endZ = endZ == null ? currCoordinate.getZ() : Math.max(endZ, currCoordinate.getZ());
+ }
+ }
+ Coordinate startCoordinate;
+ Coordinate endCoordinate;
+ if (is3d) {
+ startCoordinate = new Coordinate(startX, startY, startZ);
+ endCoordinate = new Coordinate(endX, endY, endZ);
+ } else {
+ startCoordinate = new Coordinate(startX, startY);
+ endCoordinate = new Coordinate(endX, endY);
+ }
+ return GEOMETRY_FACTORY.createLineString(new Coordinate[] {startCoordinate, endCoordinate});
+ }
+ }
+
+ public static double angle(Geometry point1, Geometry point2, Geometry point3, Geometry point4)
+ throws IllegalArgumentException {
+ if (point3 == null && point4 == null) return Functions.angle(point1, point2);
+ else if (point4 == null) return Functions.angle(point1, point2, point3);
+ if (GeomUtils.isAnyGeomEmpty(point1, point2, point3, point4))
+ throw new IllegalArgumentException("ST_Angle cannot support empty geometries.");
+ if (!(point1 instanceof Point
+ && point2 instanceof Point
+ && point3 instanceof Point
+ && point4 instanceof Point))
+ throw new IllegalArgumentException(
+ "ST_Angle supports either only POINT or only LINESTRING geometries.");
+ return GeomUtils.calcAngle(
+ point1.getCoordinate(),
+ point2.getCoordinate(),
+ point3.getCoordinate(),
+ point4.getCoordinate());
+ }
+
+ public static double angle(Geometry point1, Geometry point2, Geometry point3)
+ throws IllegalArgumentException {
+ if (GeomUtils.isAnyGeomEmpty(point1, point2, point3))
+ throw new IllegalArgumentException("ST_Angle cannot support empty geometries.");
+ if (!(point1 instanceof Point && point2 instanceof Point && point3 instanceof Point))
+ throw new IllegalArgumentException(
+ "ST_Angle supports either only POINT or only LINESTRING geometries.");
+ return GeomUtils.calcAngle(
+ point2.getCoordinate(),
+ point1.getCoordinate(),
+ point2.getCoordinate(),
+ point3.getCoordinate());
+ }
+
+ public static double angle(Geometry line1, Geometry line2) throws IllegalArgumentException {
+ if (GeomUtils.isAnyGeomEmpty(line1, line2))
+ throw new IllegalArgumentException("ST_Angle cannot support empty geometries.");
+ if (!(line1 instanceof LineString && line2 instanceof LineString))
+ throw new IllegalArgumentException(
+ "ST_Angle supports either only POINT or only LINESTRING geometries.");
+ Coordinate[] startEndLine1 = GeomUtils.getStartEndCoordinates(line1);
+ Coordinate[] startEndLine2 = GeomUtils.getStartEndCoordinates(line2);
+ assert startEndLine1 != null;
+ assert startEndLine2 != null;
+ return GeomUtils.calcAngle(
+ startEndLine1[0], startEndLine1[1], startEndLine2[0], startEndLine2[1]);
+ }
+
+ public static double degrees(double angleInRadian) {
+ return GeomUtils.toDegrees(angleInRadian);
+ }
+
+ public static Double hausdorffDistance(Geometry g1, Geometry g2, double densityFrac) {
+ return GeomUtils.getHausdorffDistance(g1, g2, densityFrac);
+ }
+
+ public static Double hausdorffDistance(Geometry g1, Geometry g2) {
+ return GeomUtils.getHausdorffDistance(g1, g2, -1);
+ }
+
+ private static IsValidOp getIsValidOpObject(Geometry geom, int flag) {
+ IsValidOp isValidOp = new IsValidOp(geom);
+
+ // Set the validity model based on flags
+ if (flag == ESRI_VALIDITY) {
+ isValidOp.setSelfTouchingRingFormingHoleValid(true);
+ } else {
+ isValidOp.setSelfTouchingRingFormingHoleValid(false);
+ }
+ return isValidOp;
+ }
+
+ public static ValidDetail isValidDetail(Geometry geom) {
+ return isValidDetail(geom, OGC_SFS_VALIDITY);
+ }
+
+ public static ValidDetail isValidDetail(Geometry geom, int flag) {
+ IsValidOp isValidOp = getIsValidOpObject(geom, flag);
+
+ if (isValidOp.isValid()) {
+ return new ValidDetail(true, null, null);
+ } else {
+ TopologyValidationError error = isValidOp.getValidationError();
+ String reason = error.toString();
+ Geometry location = geom.getFactory().createPoint(error.getCoordinate());
+ return new ValidDetail(false, reason, location);
+ }
+ }
+
+ public static String isValidReason(Geometry geom) {
+ return isValidReason(geom, OGC_SFS_VALIDITY);
+ }
+
+ public static String isValidReason(Geometry geom, int flag) {
+ IsValidOp isValidOp = getIsValidOpObject(geom, flag);
+
+ if (isValidOp.isValid()) {
+ return "Valid Geometry";
+ } else {
+ TopologyValidationError error = isValidOp.getValidationError();
+ return error.toString();
+ }
+ }
+
+ /**
+ * This method takes a GeometryCollection and returns another GeometryCollection containing the
+ * polygons formed by the linework of a set of geometries.
+ *
+ * @param geometry A collection of Geometry objects that should contain only linestrings.
+ * @return A GeometryCollection containing the resultant polygons.
+ */
+ public static Geometry polygonize(Geometry geometry) {
+ if (geometry == null || geometry.isEmpty()) {
+ return GEOMETRY_FACTORY.createGeometryCollection(null);
+ }
+
+ if (geometry instanceof GeometryCollection) {
+ Polygonizer polygonizer = new Polygonizer();
+
+ for (int i = 0; i < geometry.getNumGeometries(); i++) {
+ polygonizer.add(geometry.getGeometryN(i));
+ }
+
+ Collection polygons = polygonizer.getPolygons();
+ Geometry[] polyArray = (Geometry[]) polygons.toArray(new Geometry[0]);
+
+ return GEOMETRY_FACTORY.createGeometryCollection(polyArray);
+ } else {
+ return GEOMETRY_FACTORY.createGeometryCollection(null);
+ }
+ }
+
+ /**
+ * Creates a MultiPoint containing all coordinates of the given geometry. Duplicates, M and Z
+ * coordinates are preserved.
+ *
+ * @param geometry The input geometry
+ * @return A MultiPoint geometry
+ */
+ public static Geometry points(Geometry geometry) {
+ if (geometry == null) {
+ return null;
+ }
+
+ // Extracting all coordinates from the geometry
+ Coordinate[] coordinates = geometry.getCoordinates();
+
+ // Creating a MultiPoint from the extracted coordinates
+ return GEOMETRY_FACTORY.createMultiPointFromCoords(coordinates);
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/FunctionsGeoTools.java b/common/src/main/java/org/apache/sedona/common/FunctionsGeoTools.java
index b47c5ce8f..1691b79ae 100644
--- a/common/src/main/java/org/apache/sedona/common/FunctionsGeoTools.java
+++ b/common/src/main/java/org/apache/sedona/common/FunctionsGeoTools.java
@@ -1,15 +1,20 @@
-/**
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sedona.common;
@@ -29,146 +34,148 @@ import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
-
-
-
public class FunctionsGeoTools {
- private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
-
- public static Geometry transform(Geometry geometry, String targetCRS)
- throws FactoryException, TransformException {
- return transform(geometry, null, targetCRS, true);
+ private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
+
+ public static Geometry transform(Geometry geometry, String targetCRS)
+ throws FactoryException, TransformException {
+ return transform(geometry, null, targetCRS, true);
+ }
+
+ public static Geometry transform(Geometry geometry, String sourceCRS, String targetCRS)
+ throws FactoryException, TransformException {
+ return transform(geometry, sourceCRS, targetCRS, true);
+ }
+
+ public static Geometry transform(
+ Geometry geometry, String sourceCRScode, String targetCRScode, boolean lenient)
+ throws FactoryException, TransformException {
+ CoordinateReferenceSystem targetCRS = parseCRSString(targetCRScode);
+ return transformToGivenTarget(geometry, sourceCRScode, targetCRS, lenient);
+ }
+
+ /**
+ * Transform a geometry from one CRS to another. If sourceCRS is not specified, it will be
+ * extracted from the geometry. If lenient is true, the transformation will be lenient. This
+ * function is used by the implicit CRS transformation in Sedona rasters.
+ *
+ * @param geometry
+ * @param sourceCRScode
+ * @param targetCRS
+ * @param lenient
+ * @return
+ * @throws FactoryException
+ * @throws TransformException
+ */
+ public static Geometry transformToGivenTarget(
+ Geometry geometry, String sourceCRScode, CoordinateReferenceSystem targetCRS, boolean lenient)
+ throws FactoryException, TransformException {
+ // If sourceCRS is not specified, try to get it from the geometry
+ if (sourceCRScode == null) {
+ int srid = geometry.getSRID();
+ if (srid != 0) {
+ sourceCRScode = "epsg:" + srid;
+ } else {
+ // If SRID is not set, throw an exception
+ throw new IllegalArgumentException(
+ "Source CRS must be specified. No SRID found on geometry.");
+ }
}
-
- public static Geometry transform(Geometry geometry, String sourceCRS, String targetCRS)
- throws FactoryException, TransformException {
- return transform(geometry, sourceCRS, targetCRS, true);
- }
-
- public static Geometry transform(Geometry geometry, String sourceCRScode, String targetCRScode, boolean lenient)
- throws FactoryException, TransformException {
- CoordinateReferenceSystem targetCRS = parseCRSString(targetCRScode);
- return transformToGivenTarget(geometry, sourceCRScode, targetCRS, lenient);
+ CoordinateReferenceSystem sourceCRS = parseCRSString(sourceCRScode);
+ // If sourceCRS and targetCRS are equal, return the geometry unchanged
+ if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
+ MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, lenient);
+ return JTS.transform(geometry, transform);
+ } else return geometry;
+ }
+
+ /**
+ * Decode SRID to CRS, forcing axis order to be lon/lat
+ *
+ * @param srid SRID
+ * @return CoordinateReferenceSystem object
+ */
+ public static CoordinateReferenceSystem sridToCRS(int srid) {
+ try {
+ return CRS.decode("EPSG:" + srid, true);
+ } catch (FactoryException e) {
+ throw new IllegalArgumentException("Cannot decode SRID " + srid, e);
}
-
- /**
- * Transform a geometry from one CRS to another. If sourceCRS is not specified, it will be
- * extracted from the geometry. If lenient is true, the transformation will be lenient.
- * This function is used by the implicit CRS transformation in Sedona rasters.
- * @param geometry
- * @param sourceCRScode
- * @param targetCRS
- * @param lenient
- * @return
- * @throws FactoryException
- * @throws TransformException
- */
- public static Geometry transformToGivenTarget(Geometry geometry, String sourceCRScode, CoordinateReferenceSystem targetCRS, boolean lenient)
- throws FactoryException, TransformException
- {
- // If sourceCRS is not specified, try to get it from the geometry
- if (sourceCRScode == null) {
- int srid = geometry.getSRID();
- if (srid != 0) {
- sourceCRScode = "epsg:" + srid;
- }
- else {
- // If SRID is not set, throw an exception
- throw new IllegalArgumentException("Source CRS must be specified. No SRID found on geometry.");
- }
- }
- CoordinateReferenceSystem sourceCRS = parseCRSString(sourceCRScode);
- // If sourceCRS and targetCRS are equal, return the geometry unchanged
- if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
- MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, lenient);
- return JTS.transform(geometry, transform);
- }
- else return geometry;
+ }
+
+ private static CoordinateReferenceSystem parseCRSString(String CRSString)
+ throws FactoryException {
+ try {
+ // Try to parse as a well-known CRS code
+ // Longitude first, then latitude
+ return CRS.decode(CRSString, true);
+ } catch (NoSuchAuthorityCodeException e) {
+ try {
+ // Try to parse as a WKT CRS string, longitude first
+ Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
+ return ReferencingFactoryFinder.getCRSFactory(hints).createFromWKT(CRSString);
+ } catch (FactoryException ex) {
+ throw new FactoryException(
+ "First failed to read as a well-known CRS code: \n"
+ + e.getMessage()
+ + "\nThen failed to read as a WKT CRS string: \n"
+ + ex.getMessage());
+ }
}
+ }
- /**
- * Decode SRID to CRS, forcing axis order to be lon/lat
- * @param srid SRID
- * @return CoordinateReferenceSystem object
- */
- public static CoordinateReferenceSystem sridToCRS(int srid) {
- try {
- return CRS.decode("EPSG:" + srid, true);
- } catch (FactoryException e) {
- throw new IllegalArgumentException("Cannot decode SRID " + srid, e);
- }
+ public static Geometry voronoiPolygons(Geometry geom, double tolerance, Geometry extendTo) {
+ if (geom == null) {
+ return null;
}
-
- private static CoordinateReferenceSystem parseCRSString(String CRSString)
- throws FactoryException
- {
- try {
- // Try to parse as a well-known CRS code
- // Longitude first, then latitude
- return CRS.decode(CRSString, true);
- }
- catch (NoSuchAuthorityCodeException e) {
- try {
- // Try to parse as a WKT CRS string, longitude first
- Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
- return ReferencingFactoryFinder.getCRSFactory(hints).createFromWKT(CRSString);
- }
- catch (FactoryException ex) {
- throw new FactoryException("First failed to read as a well-known CRS code: \n" + e.getMessage() + "\nThen failed to read as a WKT CRS string: \n" + ex.getMessage());
- }
- }
+ VoronoiDiagramBuilder builder = new VoronoiDiagramBuilder();
+ builder.setSites(geom);
+ builder.setTolerance(tolerance);
+ if (extendTo != null) {
+ builder.setClipEnvelope(extendTo.getEnvelopeInternal());
+ } else {
+ Envelope e = geom.getEnvelopeInternal();
+ e.expandBy(Math.max(e.getWidth(), e.getHeight()));
+ builder.setClipEnvelope(e);
}
-
- public static Geometry voronoiPolygons(Geometry geom, double tolerance, Geometry extendTo) {
- if(geom == null) {
- return null;
- }
- VoronoiDiagramBuilder builder = new VoronoiDiagramBuilder();
- builder.setSites(geom);
- builder.setTolerance(tolerance);
- if (extendTo != null) {
- builder.setClipEnvelope(extendTo.getEnvelopeInternal());
- }
- else{
- Envelope e = geom.getEnvelopeInternal();
- e.expandBy(Math.max(e.getWidth(), e.getHeight()));
- builder.setClipEnvelope(e);
- }
- return builder.getDiagram(FunctionsGeoTools.GEOMETRY_FACTORY);
+ return builder.getDiagram(FunctionsGeoTools.GEOMETRY_FACTORY);
+ }
+
+ public static Geometry bufferSpheroid(Geometry geometry, double radius, BufferParameters params)
+ throws IllegalArgumentException {
+ // Determine the best SRID for spheroidal calculations
+ int bestCRS = Functions.bestSRID(geometry);
+ int originalCRS = geometry.getSRID();
+ final int WGS84CRS = 4326;
+
+ // Shift longitude if geometry crosses dateline
+ if (Functions.crossesDateLine(geometry)) {
+ Functions.shiftLongitude(geometry);
}
-
- public static Geometry bufferSpheroid(Geometry geometry, double radius, BufferParameters params) throws IllegalArgumentException {
- // Determine the best SRID for spheroidal calculations
- int bestCRS = Functions.bestSRID(geometry);
- int originalCRS = geometry.getSRID();
- final int WGS84CRS = 4326;
-
- // Shift longitude if geometry crosses dateline
- if (Functions.crossesDateLine(geometry)) {
- Functions.shiftLongitude(geometry);
- }
-// geometry = (Predicates.crossesDateLine(geometry)) ? Functions.shiftLongitude(geometry) : geometry;
-
- // If originalCRS is not set, use WGS84 as the originalCRS for transformation
- String sourceCRSCode = (originalCRS == 0) ? "EPSG:" + WGS84CRS : "EPSG:" + originalCRS;
- String targetCRSCode = "EPSG:" + bestCRS;
-
- try {
- // Transform the geometry to the selected SRID
- Geometry transformedGeometry = transform(geometry, sourceCRSCode, targetCRSCode);
- // Apply the buffer operation in the selected SRID
- Geometry bufferedGeometry = BufferOp.bufferOp(transformedGeometry, radius, params);
-
- // Transform back to the original SRID or to WGS 84 if original SRID was not set
- int backTransformCRSCode = (originalCRS == 0) ? WGS84CRS : originalCRS;
- Geometry bufferedResult = transform(bufferedGeometry, targetCRSCode, "EPSG:" + backTransformCRSCode);
- bufferedResult.setSRID(backTransformCRSCode);
-
- // Normalize longitudes between -180 and 180
- Functions.normalizeLongitude(bufferedResult);
- return bufferedResult;
- } catch (FactoryException | TransformException e) {
- throw new RuntimeException(e);
- }
+ // geometry = (Predicates.crossesDateLine(geometry)) ? Functions.shiftLongitude(geometry)
+ // : geometry;
+
+ // If originalCRS is not set, use WGS84 as the originalCRS for transformation
+ String sourceCRSCode = (originalCRS == 0) ? "EPSG:" + WGS84CRS : "EPSG:" + originalCRS;
+ String targetCRSCode = "EPSG:" + bestCRS;
+
+ try {
+ // Transform the geometry to the selected SRID
+ Geometry transformedGeometry = transform(geometry, sourceCRSCode, targetCRSCode);
+ // Apply the buffer operation in the selected SRID
+ Geometry bufferedGeometry = BufferOp.bufferOp(transformedGeometry, radius, params);
+
+ // Transform back to the original SRID or to WGS 84 if original SRID was not set
+ int backTransformCRSCode = (originalCRS == 0) ? WGS84CRS : originalCRS;
+ Geometry bufferedResult =
+ transform(bufferedGeometry, targetCRSCode, "EPSG:" + backTransformCRSCode);
+ bufferedResult.setSRID(backTransformCRSCode);
+
+ // Normalize longitudes between -180 and 180
+ Functions.normalizeLongitude(bufferedResult);
+ return bufferedResult;
+ } catch (FactoryException | TransformException e) {
+ throw new RuntimeException(e);
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/Predicates.java b/common/src/main/java/org/apache/sedona/common/Predicates.java
index 0eb0fa904..fb5253cac 100644
--- a/common/src/main/java/org/apache/sedona/common/Predicates.java
+++ b/common/src/main/java/org/apache/sedona/common/Predicates.java
@@ -1,79 +1,97 @@
-/**
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sedona.common;
-import org.locationtech.jts.geom.*;
import org.apache.sedona.common.sphere.Spheroid;
+import org.locationtech.jts.geom.*;
import org.locationtech.jts.operation.relate.RelateOp;
public class Predicates {
- public static boolean contains(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.contains(rightGeometry);
- }
- public static boolean intersects(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.intersects(rightGeometry);
- }
- public static boolean within(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.within(rightGeometry);
- }
- public static boolean covers(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.covers(rightGeometry);
- }
- public static boolean coveredBy(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.coveredBy(rightGeometry);
- }
- public static boolean crosses(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.crosses(rightGeometry);
- }
- public static boolean overlaps(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.overlaps(rightGeometry);
- }
- public static boolean touches(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.touches(rightGeometry);
- }
- public static boolean equals(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.symDifference(rightGeometry).isEmpty();
- }
- public static boolean disjoint(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.disjoint(rightGeometry);
- }
- public static boolean orderingEquals(Geometry leftGeometry, Geometry rightGeometry) {
- return leftGeometry.equalsExact(rightGeometry);
- }
- public static boolean dWithin(Geometry leftGeometry, Geometry rightGeometry, double distance) {
- return dWithin(leftGeometry, rightGeometry, distance, false);
- }
+ public static boolean contains(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.contains(rightGeometry);
+ }
- public static boolean dWithin(Geometry leftGeometry, Geometry rightGeometry, double distance, boolean useSpheroid) {
- if (useSpheroid) {
- double distanceSpheroid = Spheroid.distance(leftGeometry, rightGeometry);
- return distanceSpheroid <= distance;
- }else {
- return leftGeometry.isWithinDistance(rightGeometry, distance);
- }
- }
+ public static boolean intersects(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.intersects(rightGeometry);
+ }
- public static String relate(Geometry leftGeometry, Geometry rightGeometry) {
- return RelateOp.relate(leftGeometry, rightGeometry).toString();
- }
+ public static boolean within(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.within(rightGeometry);
+ }
- public static boolean relate(Geometry leftGeometry, Geometry rightGeometry, String intersectionMatrix) {
- String matrixFromGeom = relate(leftGeometry, rightGeometry);
- return IntersectionMatrix.matches(matrixFromGeom, intersectionMatrix);
- }
+ public static boolean covers(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.covers(rightGeometry);
+ }
- public static boolean relateMatch(String matrix1, String matrix2) {
- return IntersectionMatrix.matches(matrix1, matrix2);
- }
+ public static boolean coveredBy(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.coveredBy(rightGeometry);
+ }
+
+ public static boolean crosses(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.crosses(rightGeometry);
+ }
+
+ public static boolean overlaps(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.overlaps(rightGeometry);
+ }
+
+ public static boolean touches(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.touches(rightGeometry);
+ }
+
+ public static boolean equals(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.symDifference(rightGeometry).isEmpty();
+ }
+
+ public static boolean disjoint(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.disjoint(rightGeometry);
+ }
+
+ public static boolean orderingEquals(Geometry leftGeometry, Geometry rightGeometry) {
+ return leftGeometry.equalsExact(rightGeometry);
+ }
+
+ public static boolean dWithin(Geometry leftGeometry, Geometry rightGeometry, double distance) {
+ return dWithin(leftGeometry, rightGeometry, distance, false);
+ }
+
+ public static boolean dWithin(
+ Geometry leftGeometry, Geometry rightGeometry, double distance, boolean useSpheroid) {
+ if (useSpheroid) {
+ double distanceSpheroid = Spheroid.distance(leftGeometry, rightGeometry);
+ return distanceSpheroid <= distance;
+ } else {
+ return leftGeometry.isWithinDistance(rightGeometry, distance);
+ }
+ }
+
+ public static String relate(Geometry leftGeometry, Geometry rightGeometry) {
+ return RelateOp.relate(leftGeometry, rightGeometry).toString();
+ }
+
+ public static boolean relate(
+ Geometry leftGeometry, Geometry rightGeometry, String intersectionMatrix) {
+ String matrixFromGeom = relate(leftGeometry, rightGeometry);
+ return IntersectionMatrix.matches(matrixFromGeom, intersectionMatrix);
+ }
+
+ public static boolean relateMatch(String matrix1, String matrix2) {
+ return IntersectionMatrix.matches(matrix1, matrix2);
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/enums/FileDataSplitter.java b/common/src/main/java/org/apache/sedona/common/enums/FileDataSplitter.java
index 6f8921605..3e2c63e3e 100644
--- a/common/src/main/java/org/apache/sedona/common/enums/FileDataSplitter.java
+++ b/common/src/main/java/org/apache/sedona/common/enums/FileDataSplitter.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.enums;
import java.io.Serializable;
@@ -25,107 +24,90 @@ import java.util.Map;
// TODO: Auto-generated Javadoc
-/**
- * The Enum FileDataSplitter.
- */
-public enum FileDataSplitter
- implements Serializable
-{
-
- /**
- * The csv.
- */
- CSV(","),
+/** The Enum FileDataSplitter. */
+public enum FileDataSplitter implements Serializable {
- /**
- * The tsv.
- */
- TSV("\t"),
+ /** The csv. */
+ CSV(","),
- /**
- * The geojson.
- */
- GEOJSON(""),
+ /** The tsv. */
+ TSV("\t"),
- /**
- * The wkt.
- */
- WKT("\t"),
+ /** The geojson. */
+ GEOJSON(""),
- /**
- * The wkb.
- */
- WKB("\t"),
+ /** The wkt. */
+ WKT("\t"),
- COMMA(","),
+ /** The wkb. */
+ WKB("\t"),
- TAB("\t"),
+ COMMA(","),
- QUESTIONMARK("?"),
+ TAB("\t"),
- SINGLEQUOTE("\'"),
+ QUESTIONMARK("?"),
- QUOTE("\""),
+ SINGLEQUOTE("\'"),
- UNDERSCORE("_"),
+ QUOTE("\""),
- DASH("-"),
+ UNDERSCORE("_"),
- PERCENT("%"),
+ DASH("-"),
- TILDE("~"),
+ PERCENT("%"),
- PIPE("|"),
+ TILDE("~"),
- SEMICOLON(";");
+ PIPE("|"),
- /**
- * The splitter.
- */
- private final String splitter;
+ SEMICOLON(";");
- // A lookup map for getting a FileDataSplitter from a delimiter, or its name
- private static final Map<String, FileDataSplitter> lookup = new HashMap<String, FileDataSplitter>();
+ /** The splitter. */
+ private final String splitter;
- static {
- for (FileDataSplitter f : FileDataSplitter.values()) {
- lookup.put(f.getDelimiter(), f);
- lookup.put(f.name().toLowerCase(), f);
- lookup.put(f.name().toUpperCase(), f);
- }
- }
- /**
- * Instantiates a new file data splitter.
- *
- * @param splitter the splitter
- */
- FileDataSplitter(String splitter)
- {
- this.splitter = splitter;
- }
+ // A lookup map for getting a FileDataSplitter from a delimiter, or its name
+ private static final Map<String, FileDataSplitter> lookup =
+ new HashMap<String, FileDataSplitter>();
- /**
- * Gets the file data splitter.
- *
- * @param str the str
- * @return the file data splitter
- */
- public static FileDataSplitter getFileDataSplitter(String str)
- {
- FileDataSplitter f = lookup.get(str);
- if (f == null) {
- throw new IllegalArgumentException("[" + FileDataSplitter.class + "] Unsupported FileDataSplitter:" + str);
- }
- return f;
+ static {
+ for (FileDataSplitter f : FileDataSplitter.values()) {
+ lookup.put(f.getDelimiter(), f);
+ lookup.put(f.name().toLowerCase(), f);
+ lookup.put(f.name().toUpperCase(), f);
}
-
- /**
- * Gets the delimiter.
- *
- * @return the delimiter
- */
- public String getDelimiter()
- {
- return this.splitter;
+ }
+ /**
+ * Instantiates a new file data splitter.
+ *
+ * @param splitter the splitter
+ */
+ FileDataSplitter(String splitter) {
+ this.splitter = splitter;
+ }
+
+ /**
+ * Gets the file data splitter.
+ *
+ * @param str the str
+ * @return the file data splitter
+ */
+ public static FileDataSplitter getFileDataSplitter(String str) {
+ FileDataSplitter f = lookup.get(str);
+ if (f == null) {
+ throw new IllegalArgumentException(
+ "[" + FileDataSplitter.class + "] Unsupported FileDataSplitter:" + str);
}
+ return f;
+ }
+
+ /**
+ * Gets the delimiter.
+ *
+ * @return the delimiter
+ */
+ public String getDelimiter() {
+ return this.splitter;
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/enums/GeometryType.java b/common/src/main/java/org/apache/sedona/common/enums/GeometryType.java
index ba2fe97c6..b4170c7cc 100644
--- a/common/src/main/java/org/apache/sedona/common/enums/GeometryType.java
+++ b/common/src/main/java/org/apache/sedona/common/enums/GeometryType.java
@@ -16,41 +16,37 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.enums;
import java.io.Serializable;
// TODO: Auto-generated Javadoc
-/**
- * The Enum GeometryType.
- */
-public enum GeometryType
- implements Serializable
-{
-
- POINT,
- POLYGON,
- LINESTRING,
- MULTIPOINT,
- MULTIPOLYGON,
- MULTILINESTRING,
- GEOMETRYCOLLECTION,
- CIRCLE,
- RECTANGLE;
+/** The Enum GeometryType. */
+public enum GeometryType implements Serializable {
+ POINT,
+ POLYGON,
+ LINESTRING,
+ MULTIPOINT,
+ MULTIPOLYGON,
+ MULTILINESTRING,
+ GEOMETRYCOLLECTION,
+ CIRCLE,
+ RECTANGLE;
- /**
- * Gets the GeometryType.
- *
- * @param str the str
- * @return the GeometryType
- */
- public static GeometryType getGeometryType(String str)
- {
- for (GeometryType me : GeometryType.values()) {
- if (me.name().equalsIgnoreCase(str)) { return me; }
- }
- throw new IllegalArgumentException("[" + GeometryType.class + "] Unsupported geometry type:" + str);
+ /**
+ * Gets the GeometryType.
+ *
+ * @param str the str
+ * @return the GeometryType
+ */
+ public static GeometryType getGeometryType(String str) {
+ for (GeometryType me : GeometryType.values()) {
+ if (me.name().equalsIgnoreCase(str)) {
+ return me;
+ }
}
+ throw new IllegalArgumentException(
+ "[" + GeometryType.class + "] Unsupported geometry type:" + str);
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometryObjects/Circle.java b/common/src/main/java/org/apache/sedona/common/geometryObjects/Circle.java
index c0af6bc26..702b4f811 100644
--- a/common/src/main/java/org/apache/sedona/common/geometryObjects/Circle.java
+++ b/common/src/main/java/org/apache/sedona/common/geometryObjects/Circle.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometryObjects;
import org.apache.sedona.common.utils.GeomUtils;
@@ -36,486 +35,489 @@ import org.locationtech.jts.geom.Polygon;
// TODO: Auto-generated Javadoc
-/**
- * The Class Circle.
- */
-public class Circle
- extends Geometry
-{
-
- /**
- * The center.
- */
- private final Geometry centerGeometry;
- /**
- * The center point.
- */
- private final Coordinate centerPoint;
- /**
- * The radius.
- */
- private Double radius;
- /**
- * The mbr.
- */
- private Envelope MBR;
-
- /**
- * Instantiates a new circle.
- *
- * @param centerGeometry the center geometry
- * @param givenRadius the given radius
- */
- public Circle(Geometry centerGeometry, Double givenRadius)
- {
- super(new GeometryFactory(centerGeometry.getPrecisionModel()));
- this.centerGeometry = centerGeometry;
- Envelope centerGeometryMBR = this.centerGeometry.getEnvelopeInternal();
- this.centerPoint = new Coordinate((centerGeometryMBR.getMinX() + centerGeometryMBR.getMaxX()) / 2.0,
- (centerGeometryMBR.getMinY() + centerGeometryMBR.getMaxY()) / 2.0);
- // Get the internal radius of the object. We need to make sure that the circle at least should be the minimum circumscribed circle
- double width = centerGeometryMBR.getMaxX() - centerGeometryMBR.getMinX();
- double length = centerGeometryMBR.getMaxY() - centerGeometryMBR.getMinY();
- double centerGeometryInternalRadius = Math.sqrt(width * width + length * length) / 2;
- this.radius = givenRadius > centerGeometryInternalRadius ? givenRadius : centerGeometryInternalRadius;
- this.MBR = new Envelope(this.centerPoint.x - this.radius, this.centerPoint.x + this.radius, this.centerPoint.y - this.radius, this.centerPoint.y + this.radius);
- this.setUserData(centerGeometry.getUserData());
- }
-
- /**
- * Gets the center geometry.
- *
- * @return the center geometry
- */
- public Geometry getCenterGeometry()
- {
- return centerGeometry;
- }
-
- /**
- * Gets the center point.
- *
- * @return the center point
- */
- public Coordinate getCenterPoint()
- {
- return this.centerPoint;
- }
-
- /**
- * Gets the radius.
- *
- * @return the radius
- */
- public Double getRadius()
- {
- return radius;
- }
-
- /**
- * Sets the radius.
- *
- * @param givenRadius the new radius
- */
- public void setRadius(Double givenRadius)
- {
- // Get the internal radius of the object. We need to make sure that the circle at least should be the minimum circumscribed circle
- Envelope centerGeometryMBR = this.centerGeometry.getEnvelopeInternal();
- double width = centerGeometryMBR.getMaxX() - centerGeometryMBR.getMinX();
- double length = centerGeometryMBR.getMaxY() - centerGeometryMBR.getMinY();
- double centerGeometryInternalRadius = Math.sqrt(width * width + length * length) / 2;
- this.radius = givenRadius > centerGeometryInternalRadius ? givenRadius : centerGeometryInternalRadius;
- this.MBR = new Envelope(this.centerPoint.x - this.radius, this.centerPoint.x + this.radius, this.centerPoint.y - this.radius, this.centerPoint.y + this.radius);
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#covers(org.locationtech.jts.geom.Geometry)
- */
- @Override
- public boolean covers(Geometry other)
- {
- // short-circuit test
- Envelope otherEnvelope = other.getEnvelopeInternal();
- if (!getEnvelopeInternal().covers(otherEnvelope)) {
- return false;
+/** The Class Circle. */
+public class Circle extends Geometry {
+
+ /** The center. */
+ private final Geometry centerGeometry;
+ /** The center point. */
+ private final Coordinate centerPoint;
+ /** The radius. */
+ private Double radius;
+ /** The mbr. */
+ private Envelope MBR;
+
+ /**
+ * Instantiates a new circle.
+ *
+ * @param centerGeometry the center geometry
+ * @param givenRadius the given radius
+ */
+ public Circle(Geometry centerGeometry, Double givenRadius) {
+ super(new GeometryFactory(centerGeometry.getPrecisionModel()));
+ this.centerGeometry = centerGeometry;
+ Envelope centerGeometryMBR = this.centerGeometry.getEnvelopeInternal();
+ this.centerPoint =
+ new Coordinate(
+ (centerGeometryMBR.getMinX() + centerGeometryMBR.getMaxX()) / 2.0,
+ (centerGeometryMBR.getMinY() + centerGeometryMBR.getMaxY()) / 2.0);
+ // Get the internal radius of the object. We need to make sure that the circle at least should
+ // be the minimum circumscribed circle
+ double width = centerGeometryMBR.getMaxX() - centerGeometryMBR.getMinX();
+ double length = centerGeometryMBR.getMaxY() - centerGeometryMBR.getMinY();
+ double centerGeometryInternalRadius = Math.sqrt(width * width + length * length) / 2;
+ this.radius =
+ givenRadius > centerGeometryInternalRadius ? givenRadius : centerGeometryInternalRadius;
+ this.MBR =
+ new Envelope(
+ this.centerPoint.x - this.radius,
+ this.centerPoint.x + this.radius,
+ this.centerPoint.y - this.radius,
+ this.centerPoint.y + this.radius);
+ this.setUserData(centerGeometry.getUserData());
+ }
+
+ /**
+ * Gets the center geometry.
+ *
+ * @return the center geometry
+ */
+ public Geometry getCenterGeometry() {
+ return centerGeometry;
+ }
+
+ /**
+ * Gets the center point.
+ *
+ * @return the center point
+ */
+ public Coordinate getCenterPoint() {
+ return this.centerPoint;
+ }
+
+ /**
+ * Gets the radius.
+ *
+ * @return the radius
+ */
+ public Double getRadius() {
+ return radius;
+ }
+
+ /**
+ * Sets the radius.
+ *
+ * @param givenRadius the new radius
+ */
+ public void setRadius(Double givenRadius) {
+ // Get the internal radius of the object. We need to make sure that the circle at least should
+ // be the minimum circumscribed circle
+ Envelope centerGeometryMBR = this.centerGeometry.getEnvelopeInternal();
+ double width = centerGeometryMBR.getMaxX() - centerGeometryMBR.getMinX();
+ double length = centerGeometryMBR.getMaxY() - centerGeometryMBR.getMinY();
+ double centerGeometryInternalRadius = Math.sqrt(width * width + length * length) / 2;
+ this.radius =
+ givenRadius > centerGeometryInternalRadius ? givenRadius : centerGeometryInternalRadius;
+ this.MBR =
+ new Envelope(
+ this.centerPoint.x - this.radius,
+ this.centerPoint.x + this.radius,
+ this.centerPoint.y - this.radius,
+ this.centerPoint.y + this.radius);
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#covers(org.locationtech.jts.geom.Geometry)
+ */
+ @Override
+ public boolean covers(Geometry other) {
+ // short-circuit test
+ Envelope otherEnvelope = other.getEnvelopeInternal();
+ if (!getEnvelopeInternal().covers(otherEnvelope)) {
+ return false;
+ }
+
+ if (other instanceof Point) {
+ return covers((Point) other);
+ }
+
+ if (other instanceof LineString) {
+ return covers((LineString) other);
+ }
+
+ if (other instanceof Polygon) {
+ return covers(((Polygon) other).getExteriorRing());
+ }
+
+ if (other instanceof GeometryCollection) {
+ GeometryCollection collection = (GeometryCollection) other;
+ for (int i = 0; i < collection.getNumGeometries(); i++) {
+ if (!covers(collection.getGeometryN(i))) {
+ return false;
}
+ }
+ return true;
+ }
- if (other instanceof Point) {
- return covers((Point) other);
- }
+ throw new IllegalArgumentException(
+ "Circle.covers() doesn't support geometry type " + other.getGeometryType());
+ }
- if (other instanceof LineString) {
- return covers((LineString) other);
- }
+ private boolean covers(LineString lineString) {
+ for (int i = 0; i < lineString.getNumPoints(); i++) {
+ if (!covers(lineString.getPointN(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
- if (other instanceof Polygon) {
- return covers(((Polygon) other).getExteriorRing());
- }
+ private boolean covers(Point point) {
+ double deltaX = point.getX() - centerPoint.x;
+ double deltaY = point.getY() - centerPoint.y;
- if (other instanceof GeometryCollection) {
- GeometryCollection collection = (GeometryCollection) other;
- for (int i = 0; i < collection.getNumGeometries(); i++) {
- if (!covers(collection.getGeometryN(i))) {
- return false;
- }
- }
- return true;
- }
+ return (deltaX * deltaX + deltaY * deltaY) <= radius * radius;
+ }
- throw new IllegalArgumentException("Circle.covers() doesn't support geometry type " +
- other.getGeometryType());
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#intersects(org.locationtech.jts.geom.Geometry)
+ */
+ @Override
+ public boolean intersects(Geometry other) {
+ // short-circuit test
+ Envelope otherEnvelope = other.getEnvelopeInternal();
+ if (!getEnvelopeInternal().intersects(otherEnvelope)) {
+ return false;
}
- private boolean covers(LineString lineString)
- {
- for (int i = 0; i < lineString.getNumPoints(); i++) {
- if (!covers(lineString.getPointN(i))) {
- return false;
- }
- }
- return true;
+ if (other instanceof Point) {
+ return covers((Point) other);
}
- private boolean covers(Point point)
- {
- double deltaX = point.getX() - centerPoint.x;
- double deltaY = point.getY() - centerPoint.y;
-
- return (deltaX * deltaX + deltaY * deltaY) <= radius * radius;
+ if (other instanceof LineString) {
+ return intersects((LineString) other);
}
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#intersects(org.locationtech.jts.geom.Geometry)
- */
- @Override
- public boolean intersects(Geometry other)
- {
- // short-circuit test
- Envelope otherEnvelope = other.getEnvelopeInternal();
- if (!getEnvelopeInternal().intersects(otherEnvelope)) {
- return false;
- }
-
- if (other instanceof Point) {
- return covers((Point) other);
- }
-
- if (other instanceof LineString) {
- return intersects((LineString) other);
- }
-
- if (other instanceof Polygon) {
- return intersects((Polygon) other);
- }
-
- if (other instanceof GeometryCollection) {
- GeometryCollection collection = (GeometryCollection) other;
- for (int i = 0; i < collection.getNumGeometries(); i++) {
- if (intersects(collection.getGeometryN(i))) {
- return true;
- }
- }
- return false;
- }
-
- throw new IllegalArgumentException("Circle.intersects() doesn't support geometry type " +
- other.getGeometryType());
+ if (other instanceof Polygon) {
+ return intersects((Polygon) other);
}
- private boolean intersects(Polygon polygon)
- {
- if (intersects(polygon.getExteriorRing())) {
- return true;
- }
-
- if (polygon.contains(factory.createPoint(centerPoint))) {
- return true;
- }
-
- if (polygon.getNumInteriorRing() == 0) {
- return false;
+ if (other instanceof GeometryCollection) {
+ GeometryCollection collection = (GeometryCollection) other;
+ for (int i = 0; i < collection.getNumGeometries(); i++) {
+ if (intersects(collection.getGeometryN(i))) {
+ return true;
}
+ }
+ return false;
+ }
- for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
- if (intersects(polygon.getInteriorRingN(i))) {
- return true;
- }
- }
+ throw new IllegalArgumentException(
+ "Circle.intersects() doesn't support geometry type " + other.getGeometryType());
+ }
- return false;
+ private boolean intersects(Polygon polygon) {
+ if (intersects(polygon.getExteriorRing())) {
+ return true;
}
- private boolean intersects(LineString lineString)
- {
- for (int i = 0; i < lineString.getNumPoints() - 1; i++) {
- if (intersects(lineString.getPointN(i), lineString.getPointN(i + 1))) {
- return true;
- }
- }
- return false;
+ if (polygon.contains(factory.createPoint(centerPoint))) {
+ return true;
}
- /**
- * @return true if a line from `start` to `end` intersects this circle
- */
- private boolean intersects(Point start, Point end)
- {
- double deltaX = end.getX() - start.getX();
- double deltaY = end.getY() - start.getY();
-
- double centerDeltaX = start.getX() - centerPoint.x;
- double centerDeltaY = start.getY() - centerPoint.y;
-
- // Building and solving quadractic equation: ax2 + bx + c = 0
- double a = deltaX * deltaX + deltaY * deltaY;
- double b = 2 * (deltaX * centerDeltaX + deltaY * centerDeltaY);
- double c = centerDeltaX * centerDeltaX + centerDeltaY * centerDeltaY - radius * radius;
-
- double discriminant = b * b - 4 * a * c;
+ if (polygon.getNumInteriorRing() == 0) {
+ return false;
+ }
- if (discriminant < 0) {
- return false;
- }
+ for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
+ if (intersects(polygon.getInteriorRingN(i))) {
+ return true;
+ }
+ }
- double t1 = (-b + Math.sqrt(discriminant)) / (2 * a);
- if (t1 >= 0 && t1 <= 1) {
- return true;
- }
+ return false;
+ }
- double t2 = (-b - Math.sqrt(discriminant)) / (2 * a);
- if (t2 >= 0 && t2 <= 1) {
- return true;
- }
-
- return (Math.signum(t1) != Math.signum(t2));
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getGeometryType()
- */
- @Override
- public String getGeometryType()
- {
- return "Circle";
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getCoordinate()
- */
- @Override
- public Coordinate getCoordinate()
- {
- return this.centerGeometry.getCoordinate();
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getCoordinates()
- */
- @Override
- public Coordinate[] getCoordinates()
- {
- return this.centerGeometry.getCoordinates();
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getNumPoints()
- */
- @Override
- public int getNumPoints()
- {
- return this.centerGeometry.getNumPoints();
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#isEmpty()
- */
- @Override
- public boolean isEmpty()
- {
- return this.centerGeometry.isEmpty();
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getDimension()
- */
- @Override
- public int getDimension()
- {
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getBoundary()
- */
- @Override
- public Geometry getBoundary()
- {
- return getFactory().createGeometryCollection(null);
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#getBoundaryDimension()
- */
- @Override
- public int getBoundaryDimension()
- {
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#reverse()
- */
- @Override
- public Geometry reverse()
- {
- Geometry g = this.centerGeometry.reverse();
- Circle newCircle = new Circle(g, this.radius);
- return newCircle;
- }
-
- @Override
- protected Geometry reverseInternal()
- {
- Geometry g = this.centerGeometry.reverse();
- Circle newCircle = new Circle(g, this.radius);
- return newCircle;
- }
-
- public Geometry copy()
- {
- Circle cloneCircle = new Circle(this.centerGeometry.copy(), this.radius);
- return cloneCircle;// return the clone
- }
-
- @Override
- protected Geometry copyInternal()
- {
- Circle cloneCircle = new Circle(this.centerGeometry.copy(), this.radius);
- return cloneCircle;
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#equalsExact(org.locationtech.jts.geom.Geometry, double)
- */
- @Override
- public boolean equalsExact(Geometry g, double tolerance)
- {
- String type1 = this.getGeometryType();
- String type2 = g.getGeometryType();
- double radius1 = this.radius;
- double radius2 = ((Circle) g).radius;
-
- if (type1 != type2) { return false; }
- if (radius1 != radius2) { return false; }
- return GeomUtils.equalsTopoGeom(this.centerGeometry, ((Circle) g).centerGeometry);
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.CoordinateFilter)
- */
- @Override
- public void apply(CoordinateFilter filter)
- {
- // Do nothing. This circle is not expected to be a complete geometry.
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.CoordinateSequenceFilter)
- */
- @Override
- public void apply(CoordinateSequenceFilter filter)
- {
- // Do nothing. This circle is not expected to be a complete geometry.
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.GeometryFilter)
- */
- @Override
- public void apply(GeometryFilter filter)
- {
- // Do nothing. This circle is not expected to be a complete geometry.
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.GeometryComponentFilter)
- */
- @Override
- public void apply(GeometryComponentFilter filter)
- {
- // Do nothing. This circle is not expected to be a complete geometry.
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#normalize()
- */
- @Override
- public void normalize()
- {
- // Do nothing. This circle is not expected to be a complete geometry.
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#computeEnvelopeInternal()
- */
- @Override
- protected Envelope computeEnvelopeInternal()
- {
- if (isEmpty()) {
- return new Envelope();
- }
- return this.MBR;
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#compareToSameClass(java.lang.Object)
- */
- @Override
- protected int compareToSameClass(Object other)
- {
- Envelope env = (Envelope) other;
- Envelope mbr = this.MBR;
- // compare based on numerical ordering of ordinates
- if (mbr.getMinX() < env.getMinX()) { return -1; }
- if (mbr.getMinX() > env.getMinX()) { return 1; }
- if (mbr.getMinY() < env.getMinY()) { return -1; }
- if (mbr.getMinY() > env.getMinY()) { return 1; }
- if (mbr.getMaxX() < env.getMaxX()) { return -1; }
- if (mbr.getMaxX() > env.getMaxX()) { return 1; }
- if (mbr.getMaxY() < env.getMaxY()) { return -1; }
- if (mbr.getMaxY() > env.getMaxY()) { return 1; }
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.locationtech.jts.geom.Geometry#compareToSameClass(java.lang.Object, org.locationtech.jts.geom.CoordinateSequenceComparator)
- */
- @Override
- protected int compareToSameClass(Object other, CoordinateSequenceComparator comp)
- {
- Envelope env = (Envelope) other;
- Envelope mbr = this.MBR;
- // compare based on numerical ordering of ordinates
- if (mbr.getMinX() < env.getMinX()) { return -1; }
- if (mbr.getMinX() > env.getMinX()) { return 1; }
- if (mbr.getMinY() < env.getMinY()) { return -1; }
- if (mbr.getMinY() > env.getMinY()) { return 1; }
- if (mbr.getMaxX() < env.getMaxX()) { return -1; }
- if (mbr.getMaxX() > env.getMaxX()) { return 1; }
- if (mbr.getMaxY() < env.getMaxY()) { return -1; }
- if (mbr.getMaxY() > env.getMaxY()) { return 1; }
- return 0;
- }
-
- @Override
- protected int getTypeCode()
- {
- return 0;
- }
-
- @Override
- public String toString()
- {
- return "Circle of radius " + radius + " around " + centerGeometry;
- }
+ private boolean intersects(LineString lineString) {
+ for (int i = 0; i < lineString.getNumPoints() - 1; i++) {
+ if (intersects(lineString.getPointN(i), lineString.getPointN(i + 1))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** @return true if a line from `start` to `end` intersects this circle */
+ private boolean intersects(Point start, Point end) {
+ double deltaX = end.getX() - start.getX();
+ double deltaY = end.getY() - start.getY();
+
+ double centerDeltaX = start.getX() - centerPoint.x;
+ double centerDeltaY = start.getY() - centerPoint.y;
+
+ // Building and solving quadractic equation: ax2 + bx + c = 0
+ double a = deltaX * deltaX + deltaY * deltaY;
+ double b = 2 * (deltaX * centerDeltaX + deltaY * centerDeltaY);
+ double c = centerDeltaX * centerDeltaX + centerDeltaY * centerDeltaY - radius * radius;
+
+ double discriminant = b * b - 4 * a * c;
+
+ if (discriminant < 0) {
+ return false;
+ }
+
+ double t1 = (-b + Math.sqrt(discriminant)) / (2 * a);
+ if (t1 >= 0 && t1 <= 1) {
+ return true;
+ }
+
+ double t2 = (-b - Math.sqrt(discriminant)) / (2 * a);
+ if (t2 >= 0 && t2 <= 1) {
+ return true;
+ }
+
+ return (Math.signum(t1) != Math.signum(t2));
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getGeometryType()
+ */
+ @Override
+ public String getGeometryType() {
+ return "Circle";
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getCoordinate()
+ */
+ @Override
+ public Coordinate getCoordinate() {
+ return this.centerGeometry.getCoordinate();
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getCoordinates()
+ */
+ @Override
+ public Coordinate[] getCoordinates() {
+ return this.centerGeometry.getCoordinates();
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getNumPoints()
+ */
+ @Override
+ public int getNumPoints() {
+ return this.centerGeometry.getNumPoints();
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#isEmpty()
+ */
+ @Override
+ public boolean isEmpty() {
+ return this.centerGeometry.isEmpty();
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getDimension()
+ */
+ @Override
+ public int getDimension() {
+ return 0;
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getBoundary()
+ */
+ @Override
+ public Geometry getBoundary() {
+ return getFactory().createGeometryCollection(null);
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#getBoundaryDimension()
+ */
+ @Override
+ public int getBoundaryDimension() {
+ return 0;
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#reverse()
+ */
+ @Override
+ public Geometry reverse() {
+ Geometry g = this.centerGeometry.reverse();
+ Circle newCircle = new Circle(g, this.radius);
+ return newCircle;
+ }
+
+ @Override
+ protected Geometry reverseInternal() {
+ Geometry g = this.centerGeometry.reverse();
+ Circle newCircle = new Circle(g, this.radius);
+ return newCircle;
+ }
+
+ public Geometry copy() {
+ Circle cloneCircle = new Circle(this.centerGeometry.copy(), this.radius);
+ return cloneCircle; // return the clone
+ }
+
+ @Override
+ protected Geometry copyInternal() {
+ Circle cloneCircle = new Circle(this.centerGeometry.copy(), this.radius);
+ return cloneCircle;
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#equalsExact(org.locationtech.jts.geom.Geometry, double)
+ */
+ @Override
+ public boolean equalsExact(Geometry g, double tolerance) {
+ String type1 = this.getGeometryType();
+ String type2 = g.getGeometryType();
+ double radius1 = this.radius;
+ double radius2 = ((Circle) g).radius;
+
+ if (type1 != type2) {
+ return false;
+ }
+ if (radius1 != radius2) {
+ return false;
+ }
+ return GeomUtils.equalsTopoGeom(this.centerGeometry, ((Circle) g).centerGeometry);
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.CoordinateFilter)
+ */
+ @Override
+ public void apply(CoordinateFilter filter) {
+ // Do nothing. This circle is not expected to be a complete geometry.
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.CoordinateSequenceFilter)
+ */
+ @Override
+ public void apply(CoordinateSequenceFilter filter) {
+ // Do nothing. This circle is not expected to be a complete geometry.
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.GeometryFilter)
+ */
+ @Override
+ public void apply(GeometryFilter filter) {
+ // Do nothing. This circle is not expected to be a complete geometry.
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#apply(org.locationtech.jts.geom.GeometryComponentFilter)
+ */
+ @Override
+ public void apply(GeometryComponentFilter filter) {
+ // Do nothing. This circle is not expected to be a complete geometry.
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#normalize()
+ */
+ @Override
+ public void normalize() {
+ // Do nothing. This circle is not expected to be a complete geometry.
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#computeEnvelopeInternal()
+ */
+ @Override
+ protected Envelope computeEnvelopeInternal() {
+ if (isEmpty()) {
+ return new Envelope();
+ }
+ return this.MBR;
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#compareToSameClass(java.lang.Object)
+ */
+ @Override
+ protected int compareToSameClass(Object other) {
+ Envelope env = (Envelope) other;
+ Envelope mbr = this.MBR;
+ // compare based on numerical ordering of ordinates
+ if (mbr.getMinX() < env.getMinX()) {
+ return -1;
+ }
+ if (mbr.getMinX() > env.getMinX()) {
+ return 1;
+ }
+ if (mbr.getMinY() < env.getMinY()) {
+ return -1;
+ }
+ if (mbr.getMinY() > env.getMinY()) {
+ return 1;
+ }
+ if (mbr.getMaxX() < env.getMaxX()) {
+ return -1;
+ }
+ if (mbr.getMaxX() > env.getMaxX()) {
+ return 1;
+ }
+ if (mbr.getMaxY() < env.getMaxY()) {
+ return -1;
+ }
+ if (mbr.getMaxY() > env.getMaxY()) {
+ return 1;
+ }
+ return 0;
+ }
+
+ /* (non-Javadoc)
+ * @see org.locationtech.jts.geom.Geometry#compareToSameClass(java.lang.Object, org.locationtech.jts.geom.CoordinateSequenceComparator)
+ */
+ @Override
+ protected int compareToSameClass(Object other, CoordinateSequenceComparator comp) {
+ Envelope env = (Envelope) other;
+ Envelope mbr = this.MBR;
+ // compare based on numerical ordering of ordinates
+ if (mbr.getMinX() < env.getMinX()) {
+ return -1;
+ }
+ if (mbr.getMinX() > env.getMinX()) {
+ return 1;
+ }
+ if (mbr.getMinY() < env.getMinY()) {
+ return -1;
+ }
+ if (mbr.getMinY() > env.getMinY()) {
+ return 1;
+ }
+ if (mbr.getMaxX() < env.getMaxX()) {
+ return -1;
+ }
+ if (mbr.getMaxX() > env.getMaxX()) {
+ return 1;
+ }
+ if (mbr.getMaxY() < env.getMaxY()) {
+ return -1;
+ }
+ if (mbr.getMaxY() > env.getMaxY()) {
+ return 1;
+ }
+ return 0;
+ }
+
+ @Override
+ protected int getTypeCode() {
+ return 0;
+ }
+
+ @Override
+ public String toString() {
+ return "Circle of radius " + radius + " around " + centerGeometry;
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/ByteBufferGeometryBuffer.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/ByteBufferGeometryBuffer.java
index a0881d99e..e603c67a0 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/ByteBufferGeometryBuffer.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/ByteBufferGeometryBuffer.java
@@ -16,12 +16,10 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateXY;
@@ -30,235 +28,235 @@ import org.locationtech.jts.geom.CoordinateXYZM;
import org.locationtech.jts.geom.impl.CoordinateArraySequence;
class ByteBufferGeometryBuffer implements GeometryBuffer {
- private CoordinateType coordinateType = CoordinateType.XY;
- private final ByteBuffer byteBuffer;
- private int markOffset = 0;
+ private CoordinateType coordinateType = CoordinateType.XY;
+ private final ByteBuffer byteBuffer;
+ private int markOffset = 0;
- public ByteBufferGeometryBuffer(int bufferSize) {
- byteBuffer = ByteBuffer.allocate(bufferSize);
- byteBuffer.order(ByteOrder.nativeOrder());
- }
+ public ByteBufferGeometryBuffer(int bufferSize) {
+ byteBuffer = ByteBuffer.allocate(bufferSize);
+ byteBuffer.order(ByteOrder.nativeOrder());
+ }
- public ByteBufferGeometryBuffer(byte[] bytes) {
- byteBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());
- }
+ public ByteBufferGeometryBuffer(byte[] bytes) {
+ byteBuffer = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());
+ }
- public ByteBufferGeometryBuffer(ByteBuffer byteBuffer) {
- this.byteBuffer = byteBuffer.order(ByteOrder.nativeOrder());
- }
+ public ByteBufferGeometryBuffer(ByteBuffer byteBuffer) {
+ this.byteBuffer = byteBuffer.order(ByteOrder.nativeOrder());
+ }
- @Override
- public CoordinateType getCoordinateType() {
- return coordinateType;
- }
+ @Override
+ public CoordinateType getCoordinateType() {
+ return coordinateType;
+ }
- @Override
- public void setCoordinateType(CoordinateType coordinateType) {
- this.coordinateType = coordinateType;
- }
+ @Override
+ public void setCoordinateType(CoordinateType coordinateType) {
+ this.coordinateType = coordinateType;
+ }
- @Override
- public int getLength() {
- return byteBuffer.capacity();
- }
+ @Override
+ public int getLength() {
+ return byteBuffer.capacity();
+ }
- @Override
- public void mark(int offset) {
- markOffset = offset;
- }
+ @Override
+ public void mark(int offset) {
+ markOffset = offset;
+ }
- @Override
- public int getMark() {
- return markOffset;
- }
+ @Override
+ public int getMark() {
+ return markOffset;
+ }
- @Override
- public void putByte(int offset, byte value) {
- byteBuffer.put(offset, value);
- }
+ @Override
+ public void putByte(int offset, byte value) {
+ byteBuffer.put(offset, value);
+ }
- @Override
- public byte getByte(int offset) {
- return byteBuffer.get(offset);
- }
+ @Override
+ public byte getByte(int offset) {
+ return byteBuffer.get(offset);
+ }
- @Override
- public void putBytes(int offset, byte[] bytes) {
- byteBuffer.position(offset);
- byteBuffer.put(bytes, 0, bytes.length);
- }
+ @Override
+ public void putBytes(int offset, byte[] bytes) {
+ byteBuffer.position(offset);
+ byteBuffer.put(bytes, 0, bytes.length);
+ }
- @Override
- public void getBytes(byte[] bytes, int offset, int length) {
- byteBuffer.position(offset);
- byteBuffer.get(bytes, 0, length);
- }
+ @Override
+ public void getBytes(byte[] bytes, int offset, int length) {
+ byteBuffer.position(offset);
+ byteBuffer.get(bytes, 0, length);
+ }
+
+ @Override
+ public void putInt(int offset, int value) {
+ byteBuffer.putInt(offset, value);
+ }
- @Override
- public void putInt(int offset, int value) {
- byteBuffer.putInt(offset, value);
+ @Override
+ public int getInt(int offset) {
+ return byteBuffer.getInt(offset);
+ }
+
+ @Override
+ public void putCoordinate(int offset, Coordinate coordinate) {
+ byteBuffer.putDouble(offset, coordinate.x);
+ byteBuffer.putDouble(offset + 8, coordinate.y);
+ offset += 16;
+ if (coordinateType.hasZ) {
+ byteBuffer.putDouble(offset, coordinate.getZ());
+ offset += 8;
+ }
+ if (coordinateType.hasM) {
+ byteBuffer.putDouble(offset, coordinate.getM());
}
+ }
- @Override
- public int getInt(int offset) {
- return byteBuffer.getInt(offset);
+ @Override
+ public CoordinateSequence getCoordinate(int offset) {
+ double x = byteBuffer.getDouble(offset);
+ double y = byteBuffer.getDouble(offset + 8);
+ double z;
+ double m;
+ Coordinate[] coordinates = new Coordinate[1];
+ switch (coordinateType) {
+ case XY:
+ coordinates[0] = new CoordinateXY(x, y);
+ return new CoordinateArraySequence(coordinates, 2, 0);
+ case XYZ:
+ z = byteBuffer.getDouble(offset + 16);
+ coordinates[0] = new Coordinate(x, y, z);
+ return new CoordinateArraySequence(coordinates, 3, 0);
+ case XYM:
+ m = byteBuffer.getDouble(offset + 16);
+ coordinates[0] = new CoordinateXYM(x, y, m);
+ return new CoordinateArraySequence(coordinates, 3, 1);
+ case XYZM:
+ z = byteBuffer.getDouble(offset + 16);
+ m = byteBuffer.getDouble(offset + 24);
+ coordinates[0] = new CoordinateXYZM(x, y, z, m);
+ return new CoordinateArraySequence(coordinates, 4, 1);
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ }
- @Override
- public void putCoordinate(int offset, Coordinate coordinate) {
- byteBuffer.putDouble(offset, coordinate.x);
- byteBuffer.putDouble(offset + 8, coordinate.y);
- offset += 16;
- if (coordinateType.hasZ) {
- byteBuffer.putDouble(offset, coordinate.getZ());
- offset += 8;
+ @Override
+ public void putCoordinates(int offset, CoordinateSequence coordinates) {
+ int numCoordinates = coordinates.size();
+ switch (coordinateType) {
+ case XY:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ byteBuffer.putDouble(offset, coord.x);
+ byteBuffer.putDouble(offset + 8, coord.y);
+ offset += 16;
}
- if (coordinateType.hasM) {
- byteBuffer.putDouble(offset, coordinate.getM());
+ break;
+ case XYZ:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ byteBuffer.putDouble(offset, coord.x);
+ byteBuffer.putDouble(offset + 8, coord.y);
+ byteBuffer.putDouble(offset + 16, coord.getZ());
+ offset += 24;
}
- }
-
- @Override
- public CoordinateSequence getCoordinate(int offset) {
- double x = byteBuffer.getDouble(offset);
- double y = byteBuffer.getDouble(offset + 8);
- double z;
- double m;
- Coordinate[] coordinates = new Coordinate[1];
- switch (coordinateType) {
- case XY:
- coordinates[0] = new CoordinateXY(x, y);
- return new CoordinateArraySequence(coordinates, 2, 0);
- case XYZ:
- z = byteBuffer.getDouble(offset + 16);
- coordinates[0] = new Coordinate(x, y, z);
- return new CoordinateArraySequence(coordinates, 3, 0);
- case XYM:
- m = byteBuffer.getDouble(offset + 16);
- coordinates[0] = new CoordinateXYM(x, y, m);
- return new CoordinateArraySequence(coordinates, 3, 1);
- case XYZM:
- z = byteBuffer.getDouble(offset + 16);
- m = byteBuffer.getDouble(offset + 24);
- coordinates[0] = new CoordinateXYZM(x, y, z, m);
- return new CoordinateArraySequence(coordinates, 4, 1);
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
+ break;
+ case XYM:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ byteBuffer.putDouble(offset, coord.x);
+ byteBuffer.putDouble(offset + 8, coord.y);
+ byteBuffer.putDouble(offset + 16, coord.getM());
+ offset += 24;
}
- }
-
- @Override
- public void putCoordinates(int offset, CoordinateSequence coordinates) {
- int numCoordinates = coordinates.size();
- switch (coordinateType) {
- case XY:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- byteBuffer.putDouble(offset, coord.x);
- byteBuffer.putDouble(offset + 8, coord.y);
- offset += 16;
- }
- break;
- case XYZ:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- byteBuffer.putDouble(offset, coord.x);
- byteBuffer.putDouble(offset + 8, coord.y);
- byteBuffer.putDouble(offset + 16, coord.getZ());
- offset += 24;
- }
- break;
- case XYM:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- byteBuffer.putDouble(offset, coord.x);
- byteBuffer.putDouble(offset + 8, coord.y);
- byteBuffer.putDouble(offset + 16, coord.getM());
- offset += 24;
- }
- break;
- case XYZM:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- byteBuffer.putDouble(offset, coord.x);
- byteBuffer.putDouble(offset + 8, coord.y);
- byteBuffer.putDouble(offset + 16, coord.getZ());
- byteBuffer.putDouble(offset + 24, coord.getM());
- offset += 32;
- }
- break;
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
+ break;
+ case XYZM:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ byteBuffer.putDouble(offset, coord.x);
+ byteBuffer.putDouble(offset + 8, coord.y);
+ byteBuffer.putDouble(offset + 16, coord.getZ());
+ byteBuffer.putDouble(offset + 24, coord.getM());
+ offset += 32;
}
+ break;
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ }
- @Override
- public CoordinateSequence getCoordinates(int offset, int numCoordinates) {
- Coordinate[] coordinates = new Coordinate[numCoordinates];
- int dimension = 2;
- int measures = 0;
- switch (coordinateType) {
- case XY:
- for (int k = 0; k < numCoordinates; k++) {
- double x = byteBuffer.getDouble(offset);
- double y = byteBuffer.getDouble(offset + 8);
- coordinates[k] = new CoordinateXY(x, y);
- offset += 16;
- }
- break;
- case XYZ:
- dimension = 3;
- for (int k = 0; k < numCoordinates; k++) {
- double x = byteBuffer.getDouble(offset);
- double y = byteBuffer.getDouble(offset + 8);
- double z = byteBuffer.getDouble(offset + 16);
- coordinates[k] = new Coordinate(x, y, z);
- offset += 24;
- }
- break;
- case XYM:
- dimension = 3;
- measures = 1;
- for (int k = 0; k < numCoordinates; k++) {
- double x = byteBuffer.getDouble(offset);
- double y = byteBuffer.getDouble(offset + 8);
- double m = byteBuffer.getDouble(offset + 16);
- coordinates[k] = new CoordinateXYM(x, y, m);
- offset += 24;
- }
- break;
- case XYZM:
- dimension = 4;
- measures = 1;
- for (int k = 0; k < numCoordinates; k++) {
- double x = byteBuffer.getDouble(offset);
- double y = byteBuffer.getDouble(offset + 8);
- double z = byteBuffer.getDouble(offset + 16);
- double m = byteBuffer.getDouble(offset + 24);
- coordinates[k] = new CoordinateXYZM(x, y, z, m);
- offset += 32;
- }
- break;
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
+ @Override
+ public CoordinateSequence getCoordinates(int offset, int numCoordinates) {
+ Coordinate[] coordinates = new Coordinate[numCoordinates];
+ int dimension = 2;
+ int measures = 0;
+ switch (coordinateType) {
+ case XY:
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = byteBuffer.getDouble(offset);
+ double y = byteBuffer.getDouble(offset + 8);
+ coordinates[k] = new CoordinateXY(x, y);
+ offset += 16;
+ }
+ break;
+ case XYZ:
+ dimension = 3;
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = byteBuffer.getDouble(offset);
+ double y = byteBuffer.getDouble(offset + 8);
+ double z = byteBuffer.getDouble(offset + 16);
+ coordinates[k] = new Coordinate(x, y, z);
+ offset += 24;
+ }
+ break;
+ case XYM:
+ dimension = 3;
+ measures = 1;
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = byteBuffer.getDouble(offset);
+ double y = byteBuffer.getDouble(offset + 8);
+ double m = byteBuffer.getDouble(offset + 16);
+ coordinates[k] = new CoordinateXYM(x, y, m);
+ offset += 24;
}
- return new CoordinateArraySequence(coordinates, dimension, measures);
+ break;
+ case XYZM:
+ dimension = 4;
+ measures = 1;
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = byteBuffer.getDouble(offset);
+ double y = byteBuffer.getDouble(offset + 8);
+ double z = byteBuffer.getDouble(offset + 16);
+ double m = byteBuffer.getDouble(offset + 24);
+ coordinates[k] = new CoordinateXYZM(x, y, z, m);
+ offset += 32;
+ }
+ break;
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ return new CoordinateArraySequence(coordinates, dimension, measures);
+ }
- @Override
- public GeometryBuffer slice(int offset) {
- byteBuffer.position(offset);
- return new ByteBufferGeometryBuffer(byteBuffer.slice());
- }
+ @Override
+ public GeometryBuffer slice(int offset) {
+ byteBuffer.position(offset);
+ return new ByteBufferGeometryBuffer(byteBuffer.slice());
+ }
- @Override
- public byte[] toByteArray() {
- if (byteBuffer.arrayOffset() == 0) {
- return byteBuffer.array();
- } else {
- byte[] bytes = new byte[byteBuffer.capacity()];
- byteBuffer.get(bytes);
- return bytes;
- }
+ @Override
+ public byte[] toByteArray() {
+ if (byteBuffer.arrayOffset() == 0) {
+ return byteBuffer.array();
+ } else {
+ byte[] bytes = new byte[byteBuffer.capacity()];
+ byteBuffer.get(bytes);
+ return bytes;
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/CoordinateType.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/CoordinateType.java
index b89d2e490..f9ddca449 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/CoordinateType.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/CoordinateType.java
@@ -16,41 +16,40 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
enum CoordinateType {
- XY(1, 2, false, false),
- XYZ(2, 3, true, false),
- XYM(3, 3, false, true),
- XYZM(4, 4, true, true);
+ XY(1, 2, false, false),
+ XYZ(2, 3, true, false),
+ XYM(3, 3, false, true),
+ XYZM(4, 4, true, true);
- public final int value;
- public final int ordinates;
- public final boolean hasZ;
- public final boolean hasM;
- public final int bytes;
+ public final int value;
+ public final int ordinates;
+ public final boolean hasZ;
+ public final boolean hasM;
+ public final int bytes;
- CoordinateType(int value, int ordinates, boolean hasZ, boolean hasM) {
- this.value = value;
- this.ordinates = ordinates;
- this.hasZ = hasZ;
- this.hasM = hasM;
- this.bytes = 8 * ordinates;
- }
+ CoordinateType(int value, int ordinates, boolean hasZ, boolean hasM) {
+ this.value = value;
+ this.ordinates = ordinates;
+ this.hasZ = hasZ;
+ this.hasM = hasM;
+ this.bytes = 8 * ordinates;
+ }
- public static CoordinateType valueOf(int value) {
- switch (value) {
- case 1:
- return XY;
- case 2:
- return XYZ;
- case 3:
- return XYM;
- case 4:
- return XYZM;
- default:
- throw new IllegalArgumentException("Invalid coordinate type value: " + value);
- }
+ public static CoordinateType valueOf(int value) {
+ switch (value) {
+ case 1:
+ return XY;
+ case 2:
+ return XYZ;
+ case 3:
+ return XYM;
+ case 4:
+ return XYZM;
+ default:
+ throw new IllegalArgumentException("Invalid coordinate type value: " + value);
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBuffer.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBuffer.java
index d8bdc74e5..520b313c7 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBuffer.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBuffer.java
@@ -16,44 +16,43 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
interface GeometryBuffer {
- CoordinateType getCoordinateType();
+ CoordinateType getCoordinateType();
- void setCoordinateType(CoordinateType coordinateType);
+ void setCoordinateType(CoordinateType coordinateType);
- int getLength();
+ int getLength();
- void mark(int offset);
+ void mark(int offset);
- int getMark();
+ int getMark();
- void putByte(int offset, byte value);
+ void putByte(int offset, byte value);
- byte getByte(int offset);
+ byte getByte(int offset);
- void putBytes(int offset, byte[] bytes);
+ void putBytes(int offset, byte[] bytes);
- void getBytes(byte[] bytes, int offset, int length);
+ void getBytes(byte[] bytes, int offset, int length);
- void putInt(int offset, int value);
+ void putInt(int offset, int value);
- int getInt(int offset);
+ int getInt(int offset);
- void putCoordinate(int offset, Coordinate coordinate);
+ void putCoordinate(int offset, Coordinate coordinate);
- CoordinateSequence getCoordinate(int offset);
+ CoordinateSequence getCoordinate(int offset);
- void putCoordinates(int offset, CoordinateSequence coordinates);
+ void putCoordinates(int offset, CoordinateSequence coordinates);
- CoordinateSequence getCoordinates(int offset, int numCoordinates);
+ CoordinateSequence getCoordinates(int offset, int numCoordinates);
- GeometryBuffer slice(int offset);
+ GeometryBuffer slice(int offset);
- byte[] toByteArray();
+ byte[] toByteArray();
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBufferFactory.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBufferFactory.java
index 695e1bd50..a113ad448 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBufferFactory.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometryBufferFactory.java
@@ -16,51 +16,50 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
public class GeometryBufferFactory {
- private static boolean enableUnsafeGeometryBuffer = true;
+ private static boolean enableUnsafeGeometryBuffer = true;
- public static void toggleUnsafeGeometryBuffer(boolean enabled) {
- enableUnsafeGeometryBuffer = enabled;
- }
+ public static void toggleUnsafeGeometryBuffer(boolean enabled) {
+ enableUnsafeGeometryBuffer = enabled;
+ }
- public static GeometryBuffer create(int bufferSize) {
- if (UnsafeGeometryBuffer.isUnsafeAvailable() && enableUnsafeGeometryBuffer) {
- return new UnsafeGeometryBuffer(bufferSize);
- } else {
- return new ByteBufferGeometryBuffer(bufferSize);
- }
+ public static GeometryBuffer create(int bufferSize) {
+ if (UnsafeGeometryBuffer.isUnsafeAvailable() && enableUnsafeGeometryBuffer) {
+ return new UnsafeGeometryBuffer(bufferSize);
+ } else {
+ return new ByteBufferGeometryBuffer(bufferSize);
}
+ }
- public static GeometryBuffer create(String bufferType, int bufferSize) {
- switch (bufferType) {
- case "bytebuffer":
- return new ByteBufferGeometryBuffer(bufferSize);
- case "unsafe":
- return new UnsafeGeometryBuffer(bufferSize);
- default:
- throw new IllegalArgumentException("Unknown buffer type: " + bufferType);
- }
+ public static GeometryBuffer create(String bufferType, int bufferSize) {
+ switch (bufferType) {
+ case "bytebuffer":
+ return new ByteBufferGeometryBuffer(bufferSize);
+ case "unsafe":
+ return new UnsafeGeometryBuffer(bufferSize);
+ default:
+ throw new IllegalArgumentException("Unknown buffer type: " + bufferType);
}
+ }
- public static GeometryBuffer wrap(byte[] bytes) {
- if (UnsafeGeometryBuffer.isUnsafeAvailable() && enableUnsafeGeometryBuffer) {
- return new UnsafeGeometryBuffer(bytes);
- } else {
- return new ByteBufferGeometryBuffer(bytes);
- }
+ public static GeometryBuffer wrap(byte[] bytes) {
+ if (UnsafeGeometryBuffer.isUnsafeAvailable() && enableUnsafeGeometryBuffer) {
+ return new UnsafeGeometryBuffer(bytes);
+ } else {
+ return new ByteBufferGeometryBuffer(bytes);
}
+ }
- public static GeometryBuffer wrap(String bufferType, byte[] bytes) {
- switch (bufferType) {
- case "bytebuffer":
- return new ByteBufferGeometryBuffer(bytes);
- case "unsafe":
- return new UnsafeGeometryBuffer(bytes);
- default:
- throw new IllegalArgumentException("Unknown buffer type: " + bufferType);
- }
+ public static GeometryBuffer wrap(String bufferType, byte[] bytes) {
+ switch (bufferType) {
+ case "bytebuffer":
+ return new ByteBufferGeometryBuffer(bytes);
+ case "unsafe":
+ return new UnsafeGeometryBuffer(bytes);
+ default:
+ throw new IllegalArgumentException("Unknown buffer type: " + bufferType);
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerde.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerde.java
index 0b779e2f1..1df9164a6 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerde.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerde.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
import com.esotericsoftware.kryo.Kryo;
@@ -24,8 +23,8 @@ import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
+import java.io.Serializable;
import org.apache.sedona.common.geometryObjects.Circle;
-import org.apache.sedona.common.geometrySerde.GeometrySerializer;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
@@ -33,143 +32,130 @@ import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
-import java.io.Serializable;
-
/**
* Provides methods to efficiently serialize and deserialize geometry types.
- * <p>
- * Supports Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon,
+ *
+ * <p>Supports Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon,
* GeometryCollection, Circle and Envelope types.
- * <p>
- * First byte contains {@link Type#id}. Then go type-specific bytes, followed
- * by user-data attached to the geometry.
+ *
+ * <p>First byte contains {@link Type#id}. Then go type-specific bytes, followed by user-data
+ * attached to the geometry.
*/
-public class GeometrySerde
- extends Serializer implements Serializable
-{
- @Override
- public void write(Kryo kryo, Output out, Object object)
- {
- if (object instanceof Circle) {
- Circle circle = (Circle) object;
- writeType(out, Type.CIRCLE);
- out.writeDouble(circle.getRadius());
- writeGeometry(kryo, out, circle.getCenterGeometry());
- writeUserData(kryo, out, circle);
- }
- else if (object instanceof Point || object instanceof LineString
- || object instanceof Polygon || object instanceof GeometryCollection) {
- writeType(out, Type.SHAPE);
- writeGeometry(kryo, out, (Geometry) object);
- }
- else if (object instanceof Envelope) {
- Envelope envelope = (Envelope) object;
- writeType(out, Type.ENVELOPE);
- out.writeDouble(envelope.getMinX());
- out.writeDouble(envelope.getMaxX());
- out.writeDouble(envelope.getMinY());
- out.writeDouble(envelope.getMaxY());
- }
- else {
- throw new UnsupportedOperationException("Cannot serialize object of type " +
- object.getClass().getName());
- }
+public class GeometrySerde extends Serializer implements Serializable {
+ @Override
+ public void write(Kryo kryo, Output out, Object object) {
+ if (object instanceof Circle) {
+ Circle circle = (Circle) object;
+ writeType(out, Type.CIRCLE);
+ out.writeDouble(circle.getRadius());
+ writeGeometry(kryo, out, circle.getCenterGeometry());
+ writeUserData(kryo, out, circle);
+ } else if (object instanceof Point
+ || object instanceof LineString
+ || object instanceof Polygon
+ || object instanceof GeometryCollection) {
+ writeType(out, Type.SHAPE);
+ writeGeometry(kryo, out, (Geometry) object);
+ } else if (object instanceof Envelope) {
+ Envelope envelope = (Envelope) object;
+ writeType(out, Type.ENVELOPE);
+ out.writeDouble(envelope.getMinX());
+ out.writeDouble(envelope.getMaxX());
+ out.writeDouble(envelope.getMinY());
+ out.writeDouble(envelope.getMaxY());
+ } else {
+ throw new UnsupportedOperationException(
+ "Cannot serialize object of type " + object.getClass().getName());
}
-
- private void writeType(Output out, Type type)
- {
- out.writeByte((byte) type.id);
- }
-
- private void writeGeometry(Kryo kryo, Output out, Geometry geometry)
- {
- byte[] data = GeometrySerializer.serialize(geometry);
- out.writeInt(data.length);
- out.write(data, 0, data.length);
- writeUserData(kryo, out, geometry);
+ }
+
+ private void writeType(Output out, Type type) {
+ out.writeByte((byte) type.id);
+ }
+
+ private void writeGeometry(Kryo kryo, Output out, Geometry geometry) {
+ byte[] data = GeometrySerializer.serialize(geometry);
+ out.writeInt(data.length);
+ out.write(data, 0, data.length);
+ writeUserData(kryo, out, geometry);
+ }
+
+ private void writeUserData(Kryo kryo, Output out, Geometry geometry) {
+ out.writeBoolean(geometry.getUserData() != null);
+ if (geometry.getUserData() != null) {
+ kryo.writeClass(out, geometry.getUserData().getClass());
+ kryo.writeObject(out, geometry.getUserData());
}
+ }
+
+ @Override
+ public Object read(Kryo kryo, Input input, Class aClass) {
+ byte typeId = input.readByte();
+ Type geometryType = Type.fromId(typeId);
+ switch (geometryType) {
+ case SHAPE:
+ return readGeometry(kryo, input);
+ case CIRCLE:
+ {
+ double radius = input.readDouble();
+ Geometry centerGeometry = readGeometry(kryo, input);
+ Object userData = readUserData(kryo, input);
- private void writeUserData(Kryo kryo, Output out, Geometry geometry)
- {
- out.writeBoolean(geometry.getUserData() != null);
- if (geometry.getUserData() != null) {
- kryo.writeClass(out, geometry.getUserData().getClass());
- kryo.writeObject(out, geometry.getUserData());
+ Circle circle = new Circle(centerGeometry, radius);
+ circle.setUserData(userData);
+ return circle;
}
- }
-
- @Override
- public Object read(Kryo kryo, Input input, Class aClass)
- {
- byte typeId = input.readByte();
- Type geometryType = Type.fromId(typeId);
- switch (geometryType) {
- case SHAPE:
- return readGeometry(kryo, input);
- case CIRCLE: {
- double radius = input.readDouble();
- Geometry centerGeometry = readGeometry(kryo, input);
- Object userData = readUserData(kryo, input);
-
- Circle circle = new Circle(centerGeometry, radius);
- circle.setUserData(userData);
- return circle;
- }
- case ENVELOPE: {
- double xMin = input.readDouble();
- double xMax = input.readDouble();
- double yMin = input.readDouble();
- double yMax = input.readDouble();
- return new Envelope(xMin, xMax, yMin, yMax);
- }
- default:
- throw new UnsupportedOperationException(
- "Cannot deserialize object of type " + geometryType);
+ case ENVELOPE:
+ {
+ double xMin = input.readDouble();
+ double xMax = input.readDouble();
+ double yMin = input.readDouble();
+ double yMax = input.readDouble();
+ return new Envelope(xMin, xMax, yMin, yMax);
}
+ default:
+ throw new UnsupportedOperationException(
+ "Cannot deserialize object of type " + geometryType);
}
+ }
- private Object readUserData(Kryo kryo, Input input)
- {
- Object userData = null;
- if (input.readBoolean()) {
- Registration clazz = kryo.readClass(input);
- userData = kryo.readObject(input, clazz.getType());
- }
- return userData;
+ private Object readUserData(Kryo kryo, Input input) {
+ Object userData = null;
+ if (input.readBoolean()) {
+ Registration clazz = kryo.readClass(input);
+ userData = kryo.readObject(input, clazz.getType());
}
-
- private Geometry readGeometry(Kryo kryo, Input input)
- {
- int length = input.readInt();
- byte[] bytes = new byte[length];
- input.readBytes(bytes);
- Geometry geometry = GeometrySerializer.deserialize(bytes);
- geometry.setUserData(readUserData(kryo, input));
- return geometry;
+ return userData;
+ }
+
+ private Geometry readGeometry(Kryo kryo, Input input) {
+ int length = input.readInt();
+ byte[] bytes = new byte[length];
+ input.readBytes(bytes);
+ Geometry geometry = GeometrySerializer.deserialize(bytes);
+ geometry.setUserData(readUserData(kryo, input));
+ return geometry;
+ }
+
+ private enum Type {
+ SHAPE(0),
+ CIRCLE(1),
+ ENVELOPE(2);
+
+ private final int id;
+
+ Type(int id) {
+ this.id = id;
}
- private enum Type
- {
- SHAPE(0),
- CIRCLE(1),
- ENVELOPE(2);
-
- private final int id;
-
- Type(int id)
- {
- this.id = id;
+ public static Type fromId(int id) {
+ for (Type type : values()) {
+ if (type.id == id) {
+ return type;
}
+ }
- public static Type fromId(int id)
- {
- for (Type type : values()) {
- if (type.id == id) {
- return type;
- }
- }
-
- return null;
- }
+ return null;
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerializer.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerializer.java
index 8b04902e8..5d337076e 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerializer.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/GeometrySerializer.java
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
import org.locationtech.jts.geom.Coordinate;
@@ -34,544 +33,544 @@ import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKBConstants;
public class GeometrySerializer {
- private static final Coordinate NULL_COORDINATE = new Coordinate(Double.NaN, Double.NaN);
- private static final GeometryFactory FACTORY = new GeometryFactory();
-
- public static byte[] serialize(Geometry geometry) {
- GeometryBuffer buffer;
- if (geometry instanceof Point) {
- buffer = serializePoint((Point) geometry);
- } else if (geometry instanceof MultiPoint) {
- buffer = serializeMultiPoint((MultiPoint) geometry);
- } else if (geometry instanceof LineString) {
- buffer = serializeLineString((LineString) geometry);
- } else if (geometry instanceof MultiLineString) {
- buffer = serializeMultiLineString((MultiLineString) geometry);
- } else if (geometry instanceof Polygon) {
- buffer = serializePolygon((Polygon) geometry);
- } else if (geometry instanceof MultiPolygon) {
- buffer = serializeMultiPolygon((MultiPolygon) geometry);
- } else if (geometry instanceof GeometryCollection) {
- buffer = serializeGeometryCollection((GeometryCollection) geometry);
- } else {
- throw new UnsupportedOperationException(
- "Geometry type is not supported: " + geometry.getClass().getSimpleName());
- }
- return buffer.toByteArray();
- }
-
- public static Geometry deserialize(byte[] bytes) {
- GeometryBuffer buffer = GeometryBufferFactory.wrap(bytes);
- return deserialize(buffer);
- }
-
- public static Geometry deserialize(GeometryBuffer buffer) {
- checkBufferSize(buffer, 8);
- int preambleByte = buffer.getByte(0) & 0xFF;
- int wkbType = preambleByte >> 4;
- CoordinateType coordType = CoordinateType.valueOf((preambleByte & 0x0F) >> 1);
- boolean hasSrid = (preambleByte & 0x01) != 0;
- buffer.setCoordinateType(coordType);
- int srid = 0;
- if (hasSrid) {
- int srid2 = (buffer.getByte(1) & 0xFF) << 16;
- int srid1 = (buffer.getByte(2) & 0xFF) << 8;
- int srid0 = buffer.getByte(3) & 0xFF;
- srid = (srid2 | srid1 | srid0);
- }
- return deserialize(buffer, wkbType, srid);
- }
-
- private static Geometry deserialize(GeometryBuffer buffer, int wkbType, int srid) {
- switch (wkbType) {
- case WKBConstants.wkbPoint:
- return deserializePoint(buffer, srid);
- case WKBConstants.wkbMultiPoint:
- return deserializeMultiPoint(buffer, srid);
- case WKBConstants.wkbLineString:
- return deserializeLineString(buffer, srid);
- case WKBConstants.wkbMultiLineString:
- return deserializeMultiLineString(buffer, srid);
- case WKBConstants.wkbPolygon:
- return deserializePolygon(buffer, srid);
- case WKBConstants.wkbMultiPolygon:
- return deserializeMultiPolygon(buffer, srid);
- case WKBConstants.wkbGeometryCollection:
- return deserializeGeometryCollection(buffer, srid);
- default:
- throw new IllegalArgumentException(
- "Cannot deserialize buffer containing unknown geometry type ID: " + wkbType);
- }
- }
-
- private static GeometryBuffer serializePoint(Point point) {
- Coordinate coordinate = point.getCoordinate();
- if (coordinate == null) {
- return createGeometryBuffer(WKBConstants.wkbPoint, CoordinateType.XY, point.getSRID(), 8, 0);
- }
- CoordinateType coordType = getCoordinateType(coordinate);
- int bufferSize = 8 + coordType.bytes;
- GeometryBuffer buffer =
- createGeometryBuffer(WKBConstants.wkbPoint, coordType, point.getSRID(), bufferSize, 1);
- buffer.putCoordinate(8, coordinate);
- return buffer;
- }
-
- private static Point deserializePoint(GeometryBuffer buffer, int srid) {
- CoordinateType coordType = buffer.getCoordinateType();
- int numCoordinates = getBoundedInt(buffer, 4);
- Point point;
- if (numCoordinates == 0) {
- point = FACTORY.createPoint();
- buffer.mark(8);
- } else {
- int bufferSize = 8 + coordType.bytes;
- checkBufferSize(buffer, bufferSize);
- CoordinateSequence coordinates = buffer.getCoordinate(8);
- point = FACTORY.createPoint(coordinates);
- buffer.mark(bufferSize);
- }
- point.setSRID(srid);
- return point;
- }
-
- private static GeometryBuffer serializeMultiPoint(MultiPoint multiPoint) {
- int numPoints = multiPoint.getNumGeometries();
- if (numPoints == 0) {
- return createGeometryBuffer(
- WKBConstants.wkbMultiPoint, CoordinateType.XY, multiPoint.getSRID(), 8, 0);
- }
- CoordinateType coordType = getCoordinateType(multiPoint);
- int bufferSize = 8 + numPoints * coordType.bytes;
- GeometryBuffer buffer =
- createGeometryBuffer(
- WKBConstants.wkbMultiPoint, coordType, multiPoint.getSRID(), bufferSize, numPoints);
- for (int k = 0; k < numPoints; k++) {
- Point point = (Point) multiPoint.getGeometryN(k);
- Coordinate coordinate = point.getCoordinate();
- int coordinateOffset = 8 + k * coordType.bytes;
- if (coordinate == null) {
- buffer.putCoordinate(coordinateOffset, NULL_COORDINATE);
- } else {
- buffer.putCoordinate(coordinateOffset, coordinate);
- }
- }
- return buffer;
- }
-
- private static MultiPoint deserializeMultiPoint(GeometryBuffer buffer, int srid) {
- CoordinateType coordType = buffer.getCoordinateType();
- int numPoints = getBoundedInt(buffer, 4);
- int bufferSize = 8 + numPoints * coordType.bytes;
- checkBufferSize(buffer, bufferSize);
- Point[] points = new Point[numPoints];
- for (int i = 0; i < numPoints; i++) {
- CoordinateSequence coordinates = buffer.getCoordinate(8 + i * coordType.bytes);
- Coordinate coordinate = coordinates.getCoordinate(0);
- if (Double.isNaN(coordinate.x)) {
- points[i] = FACTORY.createPoint();
- } else {
- points[i] = FACTORY.createPoint(coordinates);
- }
- points[i].setSRID(srid);
- }
- buffer.mark(bufferSize);
- MultiPoint multiPoint = FACTORY.createMultiPoint(points);
- multiPoint.setSRID(srid);
- return multiPoint;
- }
-
- private static GeometryBuffer serializeLineString(LineString lineString) {
- CoordinateSequence coordinates = lineString.getCoordinateSequence();
- int numCoordinates = coordinates.size();
- if (numCoordinates == 0) {
- return createGeometryBuffer(
- WKBConstants.wkbLineString, CoordinateType.XY, lineString.getSRID(), 8, 0);
- }
- CoordinateType coordType = getCoordinateType(coordinates.getCoordinate(0));
- int bufferSize = 8 + numCoordinates * coordType.bytes;
- GeometryBuffer buffer =
- createGeometryBuffer(
- WKBConstants.wkbLineString,
- coordType,
- lineString.getSRID(),
- bufferSize,
- numCoordinates);
- buffer.putCoordinates(8, coordinates);
- return buffer;
- }
-
- private static LineString deserializeLineString(GeometryBuffer buffer, int srid) {
- CoordinateType coordType = buffer.getCoordinateType();
- int numCoordinates = getBoundedInt(buffer, 4);
- int bufferSize = 8 + numCoordinates * coordType.bytes;
- checkBufferSize(buffer, bufferSize);
- CoordinateSequence coordinates = buffer.getCoordinates(8, numCoordinates);
- buffer.mark(bufferSize);
- LineString lineString = FACTORY.createLineString(coordinates);
- lineString.setSRID(srid);
- return lineString;
- }
-
- private static GeometryBuffer serializeMultiLineString(MultiLineString multiLineString) {
- int numLineStrings = multiLineString.getNumGeometries();
- CoordinateType coordType = getCoordinateType(multiLineString);
- int numCoordinates = multiLineString.getNumPoints();
- int coordsOffset = 8;
- int numOffset = 8 + numCoordinates * coordType.bytes;
- int bufferSize = numOffset + 4 + numLineStrings * 4;
- GeometryBuffer buffer =
- createGeometryBuffer(
- WKBConstants.wkbMultiLineString,
- coordType,
- multiLineString.getSRID(),
- bufferSize,
- numCoordinates);
- GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numOffset);
- serializer.writeInt(numLineStrings);
- for (int k = 0; k < numLineStrings; k++) {
- LineString ls = (LineString) multiLineString.getGeometryN(k);
- serializer.write(ls);
- }
- assert bufferSize == serializer.intsOffset;
- return buffer;
- }
-
- private static MultiLineString deserializeMultiLineString(GeometryBuffer buffer, int srid) {
- CoordinateType coordType = buffer.getCoordinateType();
- int numCoordinates = getBoundedInt(buffer, 4);
- int coordsOffset = 8;
- int numOffset = 8 + numCoordinates * coordType.bytes;
- GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numOffset);
- int numLineStrings = serializer.checkedReadBoundedInt();
- serializer.checkRemainingIntsAtLeast(numLineStrings);
- LineString[] lineStrings = new LineString[numLineStrings];
- for (int k = 0; k < numLineStrings; k++) {
- LineString ls = serializer.readLineString();
- ls.setSRID(srid);
- lineStrings[k] = ls;
- }
- serializer.markEndOfBuffer();
- MultiLineString multiLineString = FACTORY.createMultiLineString(lineStrings);
- multiLineString.setSRID(srid);
- return multiLineString;
- }
-
- private static GeometryBuffer serializePolygon(Polygon polygon) {
- LinearRing exteriorRing = polygon.getExteriorRing();
- if (exteriorRing == null || exteriorRing.isEmpty()) {
- return createGeometryBuffer(
- WKBConstants.wkbPolygon, CoordinateType.XY, polygon.getSRID(), 8, 0);
- }
- CoordinateSequence coordinates = exteriorRing.getCoordinateSequence();
- CoordinateType coordType = getCoordinateType(coordinates.getCoordinate(0));
- int numCoordinates = polygon.getNumPoints();
- int numInteriorRings = polygon.getNumInteriorRing();
- int coordsOffset = 8;
- int numRingsOffset = 8 + numCoordinates * coordType.bytes;
- int bufferSize = numRingsOffset + 4 + 4 * (numInteriorRings + 1);
- GeometryBuffer buffer =
- createGeometryBuffer(
- WKBConstants.wkbPolygon, coordType, polygon.getSRID(), bufferSize, numCoordinates);
- GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numRingsOffset);
- serializer.write(polygon);
- assert bufferSize == serializer.intsOffset;
- return buffer;
- }
-
- private static Polygon deserializePolygon(GeometryBuffer buffer, int srid) {
- CoordinateType coordType = buffer.getCoordinateType();
- int numCoordinates = getBoundedInt(buffer, 4);
- if (numCoordinates == 0) {
- buffer.mark(8);
- Polygon polygon = FACTORY.createPolygon();
- polygon.setSRID(srid);
- return polygon;
- }
- int coordsOffset = 8;
- int numRingsOffset = 8 + numCoordinates * coordType.bytes;
- GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numRingsOffset);
- Polygon polygon = serializer.readPolygon();
- serializer.markEndOfBuffer();
- polygon.setSRID(srid);
- return polygon;
- }
-
- private static GeometryBuffer serializeMultiPolygon(MultiPolygon multiPolygon) {
- int numPolygons = multiPolygon.getNumGeometries();
- int numCoordinates = 0;
- CoordinateType coordType = getCoordinateType(multiPolygon);
- int totalRings = 0;
- for (int k = 0; k < numPolygons; k++) {
- Polygon polygon = (Polygon) multiPolygon.getGeometryN(k);
- if (!polygon.isEmpty()) {
- int numRings = polygon.getNumInteriorRing() + 1;
- totalRings += numRings;
- numCoordinates += polygon.getNumPoints();
- }
- }
- int coordsOffset = 8;
- int numPolygonsOffset = 8 + numCoordinates * coordType.bytes;
- int bufferSize = numPolygonsOffset + 4 + (numPolygons * 4) + (totalRings * 4);
- GeometryBuffer buffer =
- createGeometryBuffer(
- WKBConstants.wkbMultiPolygon,
- coordType,
- multiPolygon.getSRID(),
- bufferSize,
- numCoordinates);
- GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numPolygonsOffset);
- serializer.writeInt(numPolygons);
- for (int k = 0; k < numPolygons; k++) {
- Polygon polygon = (Polygon) multiPolygon.getGeometryN(k);
- serializer.write(polygon);
- }
- assert bufferSize == serializer.intsOffset;
- return buffer;
- }
-
- private static MultiPolygon deserializeMultiPolygon(GeometryBuffer buffer, int srid) {
- CoordinateType coordType = buffer.getCoordinateType();
- int numCoordinates = getBoundedInt(buffer, 4);
- int coordsOffset = 8;
- int numPolygonsOffset = 8 + numCoordinates * coordType.bytes;
- GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numPolygonsOffset);
- int numPolygons = serializer.checkedReadBoundedInt();
- Polygon[] polygons = new Polygon[numPolygons];
- for (int k = 0; k < numPolygons; k++) {
- Polygon polygon = serializer.readPolygon();
- polygon.setSRID(srid);
- polygons[k] = polygon;
- }
- serializer.markEndOfBuffer();
- MultiPolygon multiPolygon = FACTORY.createMultiPolygon(polygons);
- multiPolygon.setSRID(srid);
- return multiPolygon;
- }
-
- private static GeometryBuffer serializeGeometryCollection(GeometryCollection geometryCollection) {
- int numGeometries = geometryCollection.getNumGeometries();
- if (numGeometries == 0) {
- return createGeometryBuffer(
- WKBConstants.wkbGeometryCollection,
- CoordinateType.XY,
- geometryCollection.getSRID(),
- 8,
- 0);
- }
- byte[][] buffers = new byte[numGeometries][];
- int totalBytes = 0;
- for (int k = 0; k < numGeometries; k++) {
- byte[] buf = serialize(geometryCollection.getGeometryN(k));
- buffers[k] = buf;
- totalBytes += alignedOffset(buf.length);
- }
- int bufferSize = 8 + totalBytes;
- GeometryBuffer buffer =
- createGeometryBuffer(
- WKBConstants.wkbGeometryCollection,
- CoordinateType.XY,
- geometryCollection.getSRID(),
- bufferSize,
- numGeometries);
- int offset = 8;
- for (int k = 0; k < numGeometries; k++) {
- byte[] buf = buffers[k];
- buffer.putBytes(offset, buf);
- offset += alignedOffset(buf.length);
- }
- assert offset == bufferSize;
- return buffer;
- }
-
- private static GeometryCollection deserializeGeometryCollection(GeometryBuffer buffer, int srid) {
- int numGeometries = getBoundedInt(buffer, 4);
- if (numGeometries == 0) {
- buffer.mark(8);
- GeometryCollection geometryCollection = FACTORY.createGeometryCollection();
- geometryCollection.setSRID(srid);
- return geometryCollection;
- }
- Geometry[] geometries = new Geometry[numGeometries];
- int offset = 8;
- for (int k = 0; k < numGeometries; k++) {
- GeometryBuffer geomBuffer = buffer.slice(offset);
- Geometry geometry = deserialize(geomBuffer);
- int geomLength = alignedOffset(geomBuffer.getMark());
- geometry.setSRID(srid);
- geometries[k] = geometry;
- offset += geomLength;
- }
- buffer.mark(offset);
- GeometryCollection geometryCollection = FACTORY.createGeometryCollection(geometries);
- geometryCollection.setSRID(srid);
- return geometryCollection;
- }
-
- private static GeometryBuffer createGeometryBuffer(
- int wkbType, CoordinateType coordType, int srid, int bufferSize, int numCoordinates) {
- GeometryBuffer buffer = GeometryBufferFactory.create(bufferSize);
- buffer.setCoordinateType(coordType);
-
- // Set header bytes [preamble][srid (3 bytes)][numCoordinates (4 bytes)]
- int hasSridBit = (srid != 0 ? 1 : 0);
- int preambleByte = (wkbType << 4) | (coordType.value << 1) | hasSridBit;
- buffer.putByte(0, (byte) preambleByte);
- if (srid != 0) {
- // Store SRID in the next 3 bytes in big endian byte order, with the highest bit set
- // indicating that SRID need to be decoded when deserializing it.
- buffer.putByte(1, (byte) (srid >> 16));
- buffer.putByte(2, (byte) (srid >> 8));
- buffer.putByte(3, (byte) srid);
- }
- buffer.putInt(4, numCoordinates);
- return buffer;
- }
-
- private static void checkBufferSize(GeometryBuffer buffer, int minimumSize) {
- if (buffer.getLength() < minimumSize) {
- throw new IllegalArgumentException("Buffer to be deserialized is incomplete");
- }
- }
-
- private static int getBoundedInt(GeometryBuffer buffer, int offset) {
- int value = buffer.getInt(offset);
- if (value < 0) {
- throw new IllegalArgumentException("Unexpected negative value encountered: " + value);
- }
- if (value > buffer.getLength()) {
- throw new IllegalArgumentException("Unexpected large value encountered: " + value);
- }
- return value;
- }
-
- private static CoordinateType getCoordinateType(Coordinate coordinate) {
- boolean hasZ = !Double.isNaN(coordinate.getZ());
- boolean hasM = !Double.isNaN(coordinate.getM());
- return getCoordinateType(hasZ, hasM);
- }
-
- private static CoordinateType getCoordinateType(Geometry geometry) {
- Coordinate coord = geometry.getCoordinate();
- if (coord != null) {
- return getCoordinateType(coord);
- } else {
- return CoordinateType.XY;
- }
- }
-
- private static CoordinateType getCoordinateType(boolean hasZ, boolean hasM) {
- if (hasZ && hasM) {
- return CoordinateType.XYZM;
- } else if (hasZ) {
- return CoordinateType.XYZ;
- } else if (hasM) {
- return CoordinateType.XYM;
- } else {
- return CoordinateType.XY;
- }
- }
-
- private static int alignedOffset(int offset) {
- return (offset + 7) & ~7;
- }
-
- static class GeomPartSerializer {
- final GeometryBuffer buffer;
- int coordsOffset;
- final int coordsEndOffset;
- int intsOffset;
-
- GeomPartSerializer(GeometryBuffer buffer, int coordsOffset, int intsOffset) {
- this.buffer = buffer;
- this.coordsOffset = coordsOffset;
- this.coordsEndOffset = intsOffset;
- this.intsOffset = intsOffset;
- }
-
- LineString readLineString() {
- CoordinateSequence coordinates = readCoordinates();
- return FACTORY.createLineString(coordinates);
- }
-
- LinearRing readRing() {
- CoordinateSequence coordinates = readCoordinates();
- return FACTORY.createLinearRing(coordinates);
- }
-
- Polygon readPolygon() {
- int numRings = checkedReadBoundedInt();
- if (numRings == 0) {
- return FACTORY.createPolygon();
- }
- checkRemainingIntsAtLeast(numRings);
- int numInteriorRings = numRings - 1;
- LinearRing shell = readRing();
- LinearRing[] holes = new LinearRing[numInteriorRings];
- for (int k = 0; k < numInteriorRings; k++) {
- holes[k] = readRing();
- }
- return FACTORY.createPolygon(shell, holes);
- }
-
- CoordinateSequence readCoordinates() {
- int numCoordinates = getBoundedInt(buffer, intsOffset);
- int newCoordsOffset = coordsOffset + buffer.getCoordinateType().bytes * numCoordinates;
- if (newCoordsOffset > coordsEndOffset) {
- throw new IllegalStateException(
- "Number of coordinates exceeds the capacity of buffer: " + numCoordinates);
- }
- CoordinateSequence coordinates = buffer.getCoordinates(coordsOffset, numCoordinates);
- coordsOffset = newCoordsOffset;
- intsOffset += 4;
- return coordinates;
- }
-
- int readBoundedInt() {
- int value = getBoundedInt(buffer, intsOffset);
- intsOffset += 4;
- return value;
- }
-
- int checkedReadBoundedInt() {
- checkBufferSize(buffer, intsOffset + 4);
- return readBoundedInt();
- }
-
- void checkRemainingIntsAtLeast(int num) {
- checkBufferSize(buffer, intsOffset + 4 * num);
- }
-
- void write(LineString lineString) {
- CoordinateSequence coordinates = lineString.getCoordinateSequence();
- int numCoordinates = coordinates.size();
- buffer.putCoordinates(coordsOffset, coordinates);
- buffer.putInt(intsOffset, numCoordinates);
- coordsOffset += numCoordinates * buffer.getCoordinateType().bytes;
- intsOffset += 4;
- }
-
- void write(Polygon polygon) {
- LinearRing exteriorRing = polygon.getExteriorRing();
- if (exteriorRing.isEmpty()) {
- writeInt(0);
- return;
- }
- int numInteriorRings = polygon.getNumInteriorRing();
- writeInt(numInteriorRings + 1);
- write(exteriorRing);
- for (int k = 0; k < numInteriorRings; k++) {
- write(polygon.getInteriorRingN(k));
- }
- }
-
- void writeInt(int value) {
- buffer.putInt(intsOffset, value);
- intsOffset += 4;
- }
-
- void markEndOfBuffer() {
- buffer.mark(intsOffset);
- }
+ private static final Coordinate NULL_COORDINATE = new Coordinate(Double.NaN, Double.NaN);
+ private static final GeometryFactory FACTORY = new GeometryFactory();
+
+ public static byte[] serialize(Geometry geometry) {
+ GeometryBuffer buffer;
+ if (geometry instanceof Point) {
+ buffer = serializePoint((Point) geometry);
+ } else if (geometry instanceof MultiPoint) {
+ buffer = serializeMultiPoint((MultiPoint) geometry);
+ } else if (geometry instanceof LineString) {
+ buffer = serializeLineString((LineString) geometry);
+ } else if (geometry instanceof MultiLineString) {
+ buffer = serializeMultiLineString((MultiLineString) geometry);
+ } else if (geometry instanceof Polygon) {
+ buffer = serializePolygon((Polygon) geometry);
+ } else if (geometry instanceof MultiPolygon) {
+ buffer = serializeMultiPolygon((MultiPolygon) geometry);
+ } else if (geometry instanceof GeometryCollection) {
+ buffer = serializeGeometryCollection((GeometryCollection) geometry);
+ } else {
+ throw new UnsupportedOperationException(
+ "Geometry type is not supported: " + geometry.getClass().getSimpleName());
+ }
+ return buffer.toByteArray();
+ }
+
+ public static Geometry deserialize(byte[] bytes) {
+ GeometryBuffer buffer = GeometryBufferFactory.wrap(bytes);
+ return deserialize(buffer);
+ }
+
+ public static Geometry deserialize(GeometryBuffer buffer) {
+ checkBufferSize(buffer, 8);
+ int preambleByte = buffer.getByte(0) & 0xFF;
+ int wkbType = preambleByte >> 4;
+ CoordinateType coordType = CoordinateType.valueOf((preambleByte & 0x0F) >> 1);
+ boolean hasSrid = (preambleByte & 0x01) != 0;
+ buffer.setCoordinateType(coordType);
+ int srid = 0;
+ if (hasSrid) {
+ int srid2 = (buffer.getByte(1) & 0xFF) << 16;
+ int srid1 = (buffer.getByte(2) & 0xFF) << 8;
+ int srid0 = buffer.getByte(3) & 0xFF;
+ srid = (srid2 | srid1 | srid0);
+ }
+ return deserialize(buffer, wkbType, srid);
+ }
+
+ private static Geometry deserialize(GeometryBuffer buffer, int wkbType, int srid) {
+ switch (wkbType) {
+ case WKBConstants.wkbPoint:
+ return deserializePoint(buffer, srid);
+ case WKBConstants.wkbMultiPoint:
+ return deserializeMultiPoint(buffer, srid);
+ case WKBConstants.wkbLineString:
+ return deserializeLineString(buffer, srid);
+ case WKBConstants.wkbMultiLineString:
+ return deserializeMultiLineString(buffer, srid);
+ case WKBConstants.wkbPolygon:
+ return deserializePolygon(buffer, srid);
+ case WKBConstants.wkbMultiPolygon:
+ return deserializeMultiPolygon(buffer, srid);
+ case WKBConstants.wkbGeometryCollection:
+ return deserializeGeometryCollection(buffer, srid);
+ default:
+ throw new IllegalArgumentException(
+ "Cannot deserialize buffer containing unknown geometry type ID: " + wkbType);
+ }
+ }
+
+ private static GeometryBuffer serializePoint(Point point) {
+ Coordinate coordinate = point.getCoordinate();
+ if (coordinate == null) {
+ return createGeometryBuffer(WKBConstants.wkbPoint, CoordinateType.XY, point.getSRID(), 8, 0);
+ }
+ CoordinateType coordType = getCoordinateType(coordinate);
+ int bufferSize = 8 + coordType.bytes;
+ GeometryBuffer buffer =
+ createGeometryBuffer(WKBConstants.wkbPoint, coordType, point.getSRID(), bufferSize, 1);
+ buffer.putCoordinate(8, coordinate);
+ return buffer;
+ }
+
+ private static Point deserializePoint(GeometryBuffer buffer, int srid) {
+ CoordinateType coordType = buffer.getCoordinateType();
+ int numCoordinates = getBoundedInt(buffer, 4);
+ Point point;
+ if (numCoordinates == 0) {
+ point = FACTORY.createPoint();
+ buffer.mark(8);
+ } else {
+ int bufferSize = 8 + coordType.bytes;
+ checkBufferSize(buffer, bufferSize);
+ CoordinateSequence coordinates = buffer.getCoordinate(8);
+ point = FACTORY.createPoint(coordinates);
+ buffer.mark(bufferSize);
+ }
+ point.setSRID(srid);
+ return point;
+ }
+
+ private static GeometryBuffer serializeMultiPoint(MultiPoint multiPoint) {
+ int numPoints = multiPoint.getNumGeometries();
+ if (numPoints == 0) {
+ return createGeometryBuffer(
+ WKBConstants.wkbMultiPoint, CoordinateType.XY, multiPoint.getSRID(), 8, 0);
+ }
+ CoordinateType coordType = getCoordinateType(multiPoint);
+ int bufferSize = 8 + numPoints * coordType.bytes;
+ GeometryBuffer buffer =
+ createGeometryBuffer(
+ WKBConstants.wkbMultiPoint, coordType, multiPoint.getSRID(), bufferSize, numPoints);
+ for (int k = 0; k < numPoints; k++) {
+ Point point = (Point) multiPoint.getGeometryN(k);
+ Coordinate coordinate = point.getCoordinate();
+ int coordinateOffset = 8 + k * coordType.bytes;
+ if (coordinate == null) {
+ buffer.putCoordinate(coordinateOffset, NULL_COORDINATE);
+ } else {
+ buffer.putCoordinate(coordinateOffset, coordinate);
+ }
+ }
+ return buffer;
+ }
+
+ private static MultiPoint deserializeMultiPoint(GeometryBuffer buffer, int srid) {
+ CoordinateType coordType = buffer.getCoordinateType();
+ int numPoints = getBoundedInt(buffer, 4);
+ int bufferSize = 8 + numPoints * coordType.bytes;
+ checkBufferSize(buffer, bufferSize);
+ Point[] points = new Point[numPoints];
+ for (int i = 0; i < numPoints; i++) {
+ CoordinateSequence coordinates = buffer.getCoordinate(8 + i * coordType.bytes);
+ Coordinate coordinate = coordinates.getCoordinate(0);
+ if (Double.isNaN(coordinate.x)) {
+ points[i] = FACTORY.createPoint();
+ } else {
+ points[i] = FACTORY.createPoint(coordinates);
+ }
+ points[i].setSRID(srid);
+ }
+ buffer.mark(bufferSize);
+ MultiPoint multiPoint = FACTORY.createMultiPoint(points);
+ multiPoint.setSRID(srid);
+ return multiPoint;
+ }
+
+ private static GeometryBuffer serializeLineString(LineString lineString) {
+ CoordinateSequence coordinates = lineString.getCoordinateSequence();
+ int numCoordinates = coordinates.size();
+ if (numCoordinates == 0) {
+ return createGeometryBuffer(
+ WKBConstants.wkbLineString, CoordinateType.XY, lineString.getSRID(), 8, 0);
+ }
+ CoordinateType coordType = getCoordinateType(coordinates.getCoordinate(0));
+ int bufferSize = 8 + numCoordinates * coordType.bytes;
+ GeometryBuffer buffer =
+ createGeometryBuffer(
+ WKBConstants.wkbLineString,
+ coordType,
+ lineString.getSRID(),
+ bufferSize,
+ numCoordinates);
+ buffer.putCoordinates(8, coordinates);
+ return buffer;
+ }
+
+ private static LineString deserializeLineString(GeometryBuffer buffer, int srid) {
+ CoordinateType coordType = buffer.getCoordinateType();
+ int numCoordinates = getBoundedInt(buffer, 4);
+ int bufferSize = 8 + numCoordinates * coordType.bytes;
+ checkBufferSize(buffer, bufferSize);
+ CoordinateSequence coordinates = buffer.getCoordinates(8, numCoordinates);
+ buffer.mark(bufferSize);
+ LineString lineString = FACTORY.createLineString(coordinates);
+ lineString.setSRID(srid);
+ return lineString;
+ }
+
+ private static GeometryBuffer serializeMultiLineString(MultiLineString multiLineString) {
+ int numLineStrings = multiLineString.getNumGeometries();
+ CoordinateType coordType = getCoordinateType(multiLineString);
+ int numCoordinates = multiLineString.getNumPoints();
+ int coordsOffset = 8;
+ int numOffset = 8 + numCoordinates * coordType.bytes;
+ int bufferSize = numOffset + 4 + numLineStrings * 4;
+ GeometryBuffer buffer =
+ createGeometryBuffer(
+ WKBConstants.wkbMultiLineString,
+ coordType,
+ multiLineString.getSRID(),
+ bufferSize,
+ numCoordinates);
+ GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numOffset);
+ serializer.writeInt(numLineStrings);
+ for (int k = 0; k < numLineStrings; k++) {
+ LineString ls = (LineString) multiLineString.getGeometryN(k);
+ serializer.write(ls);
+ }
+ assert bufferSize == serializer.intsOffset;
+ return buffer;
+ }
+
+ private static MultiLineString deserializeMultiLineString(GeometryBuffer buffer, int srid) {
+ CoordinateType coordType = buffer.getCoordinateType();
+ int numCoordinates = getBoundedInt(buffer, 4);
+ int coordsOffset = 8;
+ int numOffset = 8 + numCoordinates * coordType.bytes;
+ GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numOffset);
+ int numLineStrings = serializer.checkedReadBoundedInt();
+ serializer.checkRemainingIntsAtLeast(numLineStrings);
+ LineString[] lineStrings = new LineString[numLineStrings];
+ for (int k = 0; k < numLineStrings; k++) {
+ LineString ls = serializer.readLineString();
+ ls.setSRID(srid);
+ lineStrings[k] = ls;
+ }
+ serializer.markEndOfBuffer();
+ MultiLineString multiLineString = FACTORY.createMultiLineString(lineStrings);
+ multiLineString.setSRID(srid);
+ return multiLineString;
+ }
+
+ private static GeometryBuffer serializePolygon(Polygon polygon) {
+ LinearRing exteriorRing = polygon.getExteriorRing();
+ if (exteriorRing == null || exteriorRing.isEmpty()) {
+ return createGeometryBuffer(
+ WKBConstants.wkbPolygon, CoordinateType.XY, polygon.getSRID(), 8, 0);
+ }
+ CoordinateSequence coordinates = exteriorRing.getCoordinateSequence();
+ CoordinateType coordType = getCoordinateType(coordinates.getCoordinate(0));
+ int numCoordinates = polygon.getNumPoints();
+ int numInteriorRings = polygon.getNumInteriorRing();
+ int coordsOffset = 8;
+ int numRingsOffset = 8 + numCoordinates * coordType.bytes;
+ int bufferSize = numRingsOffset + 4 + 4 * (numInteriorRings + 1);
+ GeometryBuffer buffer =
+ createGeometryBuffer(
+ WKBConstants.wkbPolygon, coordType, polygon.getSRID(), bufferSize, numCoordinates);
+ GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numRingsOffset);
+ serializer.write(polygon);
+ assert bufferSize == serializer.intsOffset;
+ return buffer;
+ }
+
+ private static Polygon deserializePolygon(GeometryBuffer buffer, int srid) {
+ CoordinateType coordType = buffer.getCoordinateType();
+ int numCoordinates = getBoundedInt(buffer, 4);
+ if (numCoordinates == 0) {
+ buffer.mark(8);
+ Polygon polygon = FACTORY.createPolygon();
+ polygon.setSRID(srid);
+ return polygon;
+ }
+ int coordsOffset = 8;
+ int numRingsOffset = 8 + numCoordinates * coordType.bytes;
+ GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numRingsOffset);
+ Polygon polygon = serializer.readPolygon();
+ serializer.markEndOfBuffer();
+ polygon.setSRID(srid);
+ return polygon;
+ }
+
+ private static GeometryBuffer serializeMultiPolygon(MultiPolygon multiPolygon) {
+ int numPolygons = multiPolygon.getNumGeometries();
+ int numCoordinates = 0;
+ CoordinateType coordType = getCoordinateType(multiPolygon);
+ int totalRings = 0;
+ for (int k = 0; k < numPolygons; k++) {
+ Polygon polygon = (Polygon) multiPolygon.getGeometryN(k);
+ if (!polygon.isEmpty()) {
+ int numRings = polygon.getNumInteriorRing() + 1;
+ totalRings += numRings;
+ numCoordinates += polygon.getNumPoints();
+ }
+ }
+ int coordsOffset = 8;
+ int numPolygonsOffset = 8 + numCoordinates * coordType.bytes;
+ int bufferSize = numPolygonsOffset + 4 + (numPolygons * 4) + (totalRings * 4);
+ GeometryBuffer buffer =
+ createGeometryBuffer(
+ WKBConstants.wkbMultiPolygon,
+ coordType,
+ multiPolygon.getSRID(),
+ bufferSize,
+ numCoordinates);
+ GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numPolygonsOffset);
+ serializer.writeInt(numPolygons);
+ for (int k = 0; k < numPolygons; k++) {
+ Polygon polygon = (Polygon) multiPolygon.getGeometryN(k);
+ serializer.write(polygon);
+ }
+ assert bufferSize == serializer.intsOffset;
+ return buffer;
+ }
+
+ private static MultiPolygon deserializeMultiPolygon(GeometryBuffer buffer, int srid) {
+ CoordinateType coordType = buffer.getCoordinateType();
+ int numCoordinates = getBoundedInt(buffer, 4);
+ int coordsOffset = 8;
+ int numPolygonsOffset = 8 + numCoordinates * coordType.bytes;
+ GeomPartSerializer serializer = new GeomPartSerializer(buffer, coordsOffset, numPolygonsOffset);
+ int numPolygons = serializer.checkedReadBoundedInt();
+ Polygon[] polygons = new Polygon[numPolygons];
+ for (int k = 0; k < numPolygons; k++) {
+ Polygon polygon = serializer.readPolygon();
+ polygon.setSRID(srid);
+ polygons[k] = polygon;
+ }
+ serializer.markEndOfBuffer();
+ MultiPolygon multiPolygon = FACTORY.createMultiPolygon(polygons);
+ multiPolygon.setSRID(srid);
+ return multiPolygon;
+ }
+
+ private static GeometryBuffer serializeGeometryCollection(GeometryCollection geometryCollection) {
+ int numGeometries = geometryCollection.getNumGeometries();
+ if (numGeometries == 0) {
+ return createGeometryBuffer(
+ WKBConstants.wkbGeometryCollection,
+ CoordinateType.XY,
+ geometryCollection.getSRID(),
+ 8,
+ 0);
+ }
+ byte[][] buffers = new byte[numGeometries][];
+ int totalBytes = 0;
+ for (int k = 0; k < numGeometries; k++) {
+ byte[] buf = serialize(geometryCollection.getGeometryN(k));
+ buffers[k] = buf;
+ totalBytes += alignedOffset(buf.length);
+ }
+ int bufferSize = 8 + totalBytes;
+ GeometryBuffer buffer =
+ createGeometryBuffer(
+ WKBConstants.wkbGeometryCollection,
+ CoordinateType.XY,
+ geometryCollection.getSRID(),
+ bufferSize,
+ numGeometries);
+ int offset = 8;
+ for (int k = 0; k < numGeometries; k++) {
+ byte[] buf = buffers[k];
+ buffer.putBytes(offset, buf);
+ offset += alignedOffset(buf.length);
+ }
+ assert offset == bufferSize;
+ return buffer;
+ }
+
+ private static GeometryCollection deserializeGeometryCollection(GeometryBuffer buffer, int srid) {
+ int numGeometries = getBoundedInt(buffer, 4);
+ if (numGeometries == 0) {
+ buffer.mark(8);
+ GeometryCollection geometryCollection = FACTORY.createGeometryCollection();
+ geometryCollection.setSRID(srid);
+ return geometryCollection;
+ }
+ Geometry[] geometries = new Geometry[numGeometries];
+ int offset = 8;
+ for (int k = 0; k < numGeometries; k++) {
+ GeometryBuffer geomBuffer = buffer.slice(offset);
+ Geometry geometry = deserialize(geomBuffer);
+ int geomLength = alignedOffset(geomBuffer.getMark());
+ geometry.setSRID(srid);
+ geometries[k] = geometry;
+ offset += geomLength;
+ }
+ buffer.mark(offset);
+ GeometryCollection geometryCollection = FACTORY.createGeometryCollection(geometries);
+ geometryCollection.setSRID(srid);
+ return geometryCollection;
+ }
+
+ private static GeometryBuffer createGeometryBuffer(
+ int wkbType, CoordinateType coordType, int srid, int bufferSize, int numCoordinates) {
+ GeometryBuffer buffer = GeometryBufferFactory.create(bufferSize);
+ buffer.setCoordinateType(coordType);
+
+ // Set header bytes [preamble][srid (3 bytes)][numCoordinates (4 bytes)]
+ int hasSridBit = (srid != 0 ? 1 : 0);
+ int preambleByte = (wkbType << 4) | (coordType.value << 1) | hasSridBit;
+ buffer.putByte(0, (byte) preambleByte);
+ if (srid != 0) {
+ // Store SRID in the next 3 bytes in big endian byte order, with the highest bit set
+ // indicating that SRID need to be decoded when deserializing it.
+ buffer.putByte(1, (byte) (srid >> 16));
+ buffer.putByte(2, (byte) (srid >> 8));
+ buffer.putByte(3, (byte) srid);
+ }
+ buffer.putInt(4, numCoordinates);
+ return buffer;
+ }
+
+ private static void checkBufferSize(GeometryBuffer buffer, int minimumSize) {
+ if (buffer.getLength() < minimumSize) {
+ throw new IllegalArgumentException("Buffer to be deserialized is incomplete");
+ }
+ }
+
+ private static int getBoundedInt(GeometryBuffer buffer, int offset) {
+ int value = buffer.getInt(offset);
+ if (value < 0) {
+ throw new IllegalArgumentException("Unexpected negative value encountered: " + value);
+ }
+ if (value > buffer.getLength()) {
+ throw new IllegalArgumentException("Unexpected large value encountered: " + value);
+ }
+ return value;
+ }
+
+ private static CoordinateType getCoordinateType(Coordinate coordinate) {
+ boolean hasZ = !Double.isNaN(coordinate.getZ());
+ boolean hasM = !Double.isNaN(coordinate.getM());
+ return getCoordinateType(hasZ, hasM);
+ }
+
+ private static CoordinateType getCoordinateType(Geometry geometry) {
+ Coordinate coord = geometry.getCoordinate();
+ if (coord != null) {
+ return getCoordinateType(coord);
+ } else {
+ return CoordinateType.XY;
+ }
+ }
+
+ private static CoordinateType getCoordinateType(boolean hasZ, boolean hasM) {
+ if (hasZ && hasM) {
+ return CoordinateType.XYZM;
+ } else if (hasZ) {
+ return CoordinateType.XYZ;
+ } else if (hasM) {
+ return CoordinateType.XYM;
+ } else {
+ return CoordinateType.XY;
+ }
+ }
+
+ private static int alignedOffset(int offset) {
+ return (offset + 7) & ~7;
+ }
+
+ static class GeomPartSerializer {
+ final GeometryBuffer buffer;
+ int coordsOffset;
+ final int coordsEndOffset;
+ int intsOffset;
+
+ GeomPartSerializer(GeometryBuffer buffer, int coordsOffset, int intsOffset) {
+ this.buffer = buffer;
+ this.coordsOffset = coordsOffset;
+ this.coordsEndOffset = intsOffset;
+ this.intsOffset = intsOffset;
+ }
+
+ LineString readLineString() {
+ CoordinateSequence coordinates = readCoordinates();
+ return FACTORY.createLineString(coordinates);
+ }
+
+ LinearRing readRing() {
+ CoordinateSequence coordinates = readCoordinates();
+ return FACTORY.createLinearRing(coordinates);
+ }
+
+ Polygon readPolygon() {
+ int numRings = checkedReadBoundedInt();
+ if (numRings == 0) {
+ return FACTORY.createPolygon();
+ }
+ checkRemainingIntsAtLeast(numRings);
+ int numInteriorRings = numRings - 1;
+ LinearRing shell = readRing();
+ LinearRing[] holes = new LinearRing[numInteriorRings];
+ for (int k = 0; k < numInteriorRings; k++) {
+ holes[k] = readRing();
+ }
+ return FACTORY.createPolygon(shell, holes);
+ }
+
+ CoordinateSequence readCoordinates() {
+ int numCoordinates = getBoundedInt(buffer, intsOffset);
+ int newCoordsOffset = coordsOffset + buffer.getCoordinateType().bytes * numCoordinates;
+ if (newCoordsOffset > coordsEndOffset) {
+ throw new IllegalStateException(
+ "Number of coordinates exceeds the capacity of buffer: " + numCoordinates);
+ }
+ CoordinateSequence coordinates = buffer.getCoordinates(coordsOffset, numCoordinates);
+ coordsOffset = newCoordsOffset;
+ intsOffset += 4;
+ return coordinates;
+ }
+
+ int readBoundedInt() {
+ int value = getBoundedInt(buffer, intsOffset);
+ intsOffset += 4;
+ return value;
+ }
+
+ int checkedReadBoundedInt() {
+ checkBufferSize(buffer, intsOffset + 4);
+ return readBoundedInt();
+ }
+
+ void checkRemainingIntsAtLeast(int num) {
+ checkBufferSize(buffer, intsOffset + 4 * num);
+ }
+
+ void write(LineString lineString) {
+ CoordinateSequence coordinates = lineString.getCoordinateSequence();
+ int numCoordinates = coordinates.size();
+ buffer.putCoordinates(coordsOffset, coordinates);
+ buffer.putInt(intsOffset, numCoordinates);
+ coordsOffset += numCoordinates * buffer.getCoordinateType().bytes;
+ intsOffset += 4;
+ }
+
+ void write(Polygon polygon) {
+ LinearRing exteriorRing = polygon.getExteriorRing();
+ if (exteriorRing.isEmpty()) {
+ writeInt(0);
+ return;
+ }
+ int numInteriorRings = polygon.getNumInteriorRing();
+ writeInt(numInteriorRings + 1);
+ write(exteriorRing);
+ for (int k = 0; k < numInteriorRings; k++) {
+ write(polygon.getInteriorRingN(k));
+ }
+ }
+
+ void writeInt(int value) {
+ buffer.putInt(intsOffset, value);
+ intsOffset += 4;
+ }
+
+ void markEndOfBuffer() {
+ buffer.mark(intsOffset);
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/SpatialIndexSerde.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/SpatialIndexSerde.java
index efaf2e972..64ef064c2 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/SpatialIndexSerde.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/SpatialIndexSerde.java
@@ -16,115 +16,104 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
+import java.io.Serializable;
import org.locationtech.jts.index.quadtree.IndexSerde;
import org.locationtech.jts.index.quadtree.Quadtree;
import org.locationtech.jts.index.strtree.STRtree;
-import java.io.Serializable;
-
/**
* Provides methods to efficiently serialize and deserialize spatialIndex types.
- * <p>
- * Support Quadtree, STRtree types
- * <p>
- * trees are serialized recursively.
+ *
+ * <p>Support Quadtree, STRtree types
+ *
+ * <p>trees are serialized recursively.
*/
-public class SpatialIndexSerde
- extends Serializer implements Serializable
-{
-
- private final GeometrySerde geometrySerde;
-
- public SpatialIndexSerde()
- {
- super();
- geometrySerde = new GeometrySerde();
- }
-
- public SpatialIndexSerde(GeometrySerde geometrySerde)
- {
- super();
- this.geometrySerde = geometrySerde;
+public class SpatialIndexSerde extends Serializer implements Serializable {
+
+ private final GeometrySerde geometrySerde;
+
+ public SpatialIndexSerde() {
+ super();
+ geometrySerde = new GeometrySerde();
+ }
+
+ public SpatialIndexSerde(GeometrySerde geometrySerde) {
+ super();
+ this.geometrySerde = geometrySerde;
+ }
+
+ @Override
+ public void write(Kryo kryo, Output output, Object o) {
+ if (o instanceof Quadtree) {
+ // serialize quadtree index
+ writeType(output, Type.QUADTREE);
+ Quadtree tree = (Quadtree) o;
+ IndexSerde indexSerde = new IndexSerde();
+ indexSerde.write(kryo, output, tree);
+ } else if (o instanceof STRtree) {
+ // serialize rtree index
+ writeType(output, Type.RTREE);
+ STRtree tree = (STRtree) o;
+ org.locationtech.jts.index.strtree.IndexSerde indexSerde =
+ new org.locationtech.jts.index.strtree.IndexSerde();
+ indexSerde.write(kryo, output, tree);
+ } else {
+ throw new UnsupportedOperationException(" index type not supported ");
}
-
- @Override
- public void write(Kryo kryo, Output output, Object o)
- {
- if (o instanceof Quadtree) {
- // serialize quadtree index
- writeType(output, Type.QUADTREE);
- Quadtree tree = (Quadtree) o;
- IndexSerde indexSerde = new IndexSerde();
- indexSerde.write(kryo, output, tree);
- }
- else if (o instanceof STRtree) {
- //serialize rtree index
- writeType(output, Type.RTREE);
- STRtree tree = (STRtree) o;
- org.locationtech.jts.index.strtree.IndexSerde indexSerde
- = new org.locationtech.jts.index.strtree.IndexSerde();
- indexSerde.write(kryo, output, tree);
+ }
+
+ @Override
+ public Object read(Kryo kryo, Input input, Class aClass) {
+ byte typeID = input.readByte();
+ Type indexType = Type.fromId(typeID);
+ switch (indexType) {
+ case QUADTREE:
+ {
+ IndexSerde indexSerde = new IndexSerde();
+ return indexSerde.read(kryo, input);
}
- else {
- throw new UnsupportedOperationException(" index type not supported ");
+ case RTREE:
+ {
+ org.locationtech.jts.index.strtree.IndexSerde indexSerde =
+ new org.locationtech.jts.index.strtree.IndexSerde();
+ return indexSerde.read(kryo, input);
}
- }
-
- @Override
- public Object read(Kryo kryo, Input input, Class aClass)
- {
- byte typeID = input.readByte();
- Type indexType = Type.fromId(typeID);
- switch (indexType) {
- case QUADTREE: {
- IndexSerde indexSerde = new IndexSerde();
- return indexSerde.read(kryo, input);
- }
- case RTREE: {
- org.locationtech.jts.index.strtree.IndexSerde indexSerde =
- new org.locationtech.jts.index.strtree.IndexSerde();
- return indexSerde.read(kryo, input);
- }
- default: {
- throw new UnsupportedOperationException("can't deserialize spatial index of type" + indexType);
- }
+ default:
+ {
+ throw new UnsupportedOperationException(
+ "can't deserialize spatial index of type" + indexType);
}
}
+ }
- private void writeType(Output output, Type type)
- {
- output.writeByte((byte) type.id);
- }
+ private void writeType(Output output, Type type) {
+ output.writeByte((byte) type.id);
+ }
- private enum Type
- {
+ private enum Type {
+ QUADTREE(0),
+ RTREE(1);
- QUADTREE(0),
- RTREE(1);
+ private final int id;
- private final int id;
+ Type(int id) {
+ this.id = id;
+ }
- Type(int id)
- {
- this.id = id;
+ public static Type fromId(int id) {
+ for (Type type : values()) {
+ if (type.id == id) {
+ return type;
}
+ }
- public static Type fromId(int id)
- {
- for (Type type : values()) {
- if (type.id == id) {
- return type;
- }
- }
-
- return null;
- }
+ return null;
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/geometrySerde/UnsafeGeometryBuffer.java b/common/src/main/java/org/apache/sedona/common/geometrySerde/UnsafeGeometryBuffer.java
index 22772f72a..a908a932f 100644
--- a/common/src/main/java/org/apache/sedona/common/geometrySerde/UnsafeGeometryBuffer.java
+++ b/common/src/main/java/org/apache/sedona/common/geometrySerde/UnsafeGeometryBuffer.java
@@ -16,9 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sedona.common.geometrySerde;
+import java.lang.reflect.Field;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateXY;
@@ -27,293 +27,291 @@ import org.locationtech.jts.geom.CoordinateXYZM;
import org.locationtech.jts.geom.impl.CoordinateArraySequence;
import sun.misc.Unsafe;
-import java.lang.reflect.Field;
-
class UnsafeGeometryBuffer implements GeometryBuffer {
- private static final Unsafe UNSAFE;
- private static final long BYTE_ARRAY_BASE_OFFSET;
+ private static final Unsafe UNSAFE;
+ private static final long BYTE_ARRAY_BASE_OFFSET;
- static {
- Unsafe unsafe;
- long byteArrayOffset = 0;
- try {
- Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
- theUnsafe.setAccessible(true);
- unsafe = (Unsafe) theUnsafe.get(null);
- byteArrayOffset = unsafe.arrayBaseOffset(byte[].class);
- } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
- // Unsafe is not available
- unsafe = null;
- }
- UNSAFE = unsafe;
- BYTE_ARRAY_BASE_OFFSET = byteArrayOffset;
+ static {
+ Unsafe unsafe;
+ long byteArrayOffset = 0;
+ try {
+ Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
+ theUnsafe.setAccessible(true);
+ unsafe = (Unsafe) theUnsafe.get(null);
+ byteArrayOffset = unsafe.arrayBaseOffset(byte[].class);
+ } catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
+ // Unsafe is not available
+ unsafe = null;
}
+ UNSAFE = unsafe;
+ BYTE_ARRAY_BASE_OFFSET = byteArrayOffset;
+ }
- public static boolean isUnsafeAvailable() {
- return UNSAFE != null;
- }
+ public static boolean isUnsafeAvailable() {
+ return UNSAFE != null;
+ }
- private CoordinateType coordinateType = CoordinateType.XY;
- private final byte[] bytes;
- private final long baseOffset;
- private int markOffset = 0;
+ private CoordinateType coordinateType = CoordinateType.XY;
+ private final byte[] bytes;
+ private final long baseOffset;
+ private int markOffset = 0;
- public UnsafeGeometryBuffer(int bufferSize) {
- bytes = new byte[bufferSize];
- baseOffset = BYTE_ARRAY_BASE_OFFSET;
- }
+ public UnsafeGeometryBuffer(int bufferSize) {
+ bytes = new byte[bufferSize];
+ baseOffset = BYTE_ARRAY_BASE_OFFSET;
+ }
- public UnsafeGeometryBuffer(byte[] bytes, int offset) {
- this.bytes = bytes;
- baseOffset = offset + BYTE_ARRAY_BASE_OFFSET;
- }
+ public UnsafeGeometryBuffer(byte[] bytes, int offset) {
+ this.bytes = bytes;
+ baseOffset = offset + BYTE_ARRAY_BASE_OFFSET;
+ }
- public UnsafeGeometryBuffer(byte[] bytes) {
- this.bytes = bytes;
- baseOffset = BYTE_ARRAY_BASE_OFFSET;
- }
+ public UnsafeGeometryBuffer(byte[] bytes) {
+ this.bytes = bytes;
+ baseOffset = BYTE_ARRAY_BASE_OFFSET;
+ }
- @Override
- public CoordinateType getCoordinateType() {
- return coordinateType;
- }
+ @Override
+ public CoordinateType getCoordinateType() {
+ return coordinateType;
+ }
- @Override
- public void setCoordinateType(CoordinateType coordinateType) {
- this.coordinateType = coordinateType;
- }
+ @Override
+ public void setCoordinateType(CoordinateType coordinateType) {
+ this.coordinateType = coordinateType;
+ }
- @Override
- public int getLength() {
- return (int) (bytes.length - baseOffset + BYTE_ARRAY_BASE_OFFSET);
- }
+ @Override
+ public int getLength() {
+ return (int) (bytes.length - baseOffset + BYTE_ARRAY_BASE_OFFSET);
+ }
- @Override
- public void mark(int offset) {
- markOffset = offset;
- }
+ @Override
+ public void mark(int offset) {
+ markOffset = offset;
+ }
- @Override
- public int getMark() {
- return markOffset;
- }
+ @Override
+ public int getMark() {
+ return markOffset;
+ }
- @Override
- public void putByte(int offset, byte value) {
- UNSAFE.putByte(bytes, baseOffset + offset, value);
- }
+ @Override
+ public void putByte(int offset, byte value) {
+ UNSAFE.putByte(bytes, baseOffset + offset, value);
+ }
- @Override
- public byte getByte(int offset) {
- assert baseOffset + offset < bytes.length + BYTE_ARRAY_BASE_OFFSET;
- return UNSAFE.getByte(bytes, baseOffset + offset);
- }
+ @Override
+ public byte getByte(int offset) {
+ assert baseOffset + offset < bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ return UNSAFE.getByte(bytes, baseOffset + offset);
+ }
- @Override
- public void putBytes(int offset, byte[] inBytes) {
- assert baseOffset + offset + inBytes.length <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- UNSAFE.copyMemory(inBytes, BYTE_ARRAY_BASE_OFFSET, bytes, baseOffset + offset, inBytes.length);
- }
+ @Override
+ public void putBytes(int offset, byte[] inBytes) {
+ assert baseOffset + offset + inBytes.length <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ UNSAFE.copyMemory(inBytes, BYTE_ARRAY_BASE_OFFSET, bytes, baseOffset + offset, inBytes.length);
+ }
- @Override
- public void getBytes(byte[] outBytes, int offset, int length) {
- assert baseOffset + offset + length <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- UNSAFE.copyMemory(bytes, baseOffset + offset, outBytes, BYTE_ARRAY_BASE_OFFSET, length);
- }
+ @Override
+ public void getBytes(byte[] outBytes, int offset, int length) {
+ assert baseOffset + offset + length <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ UNSAFE.copyMemory(bytes, baseOffset + offset, outBytes, BYTE_ARRAY_BASE_OFFSET, length);
+ }
- @Override
- public void putInt(int offset, int value) {
- assert baseOffset + offset + 4 <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- UNSAFE.putInt(bytes, baseOffset + offset, value);
- }
+ @Override
+ public void putInt(int offset, int value) {
+ assert baseOffset + offset + 4 <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ UNSAFE.putInt(bytes, baseOffset + offset, value);
+ }
- @Override
- public int getInt(int offset) {
- assert baseOffset + offset + 4 <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- return UNSAFE.getInt(bytes, baseOffset + offset);
- }
+ @Override
+ public int getInt(int offset) {
+ assert baseOffset + offset + 4 <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ return UNSAFE.getInt(bytes, baseOffset + offset);
+ }
- @Override
- public void putCoordinate(int offset, Coordinate coordinate) {
- long coordOffset = baseOffset + offset;
- assert coordOffset + coordinateType.bytes <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- switch (coordinateType) {
- case XY:
- UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
- break;
- case XYZ:
- UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
- UNSAFE.putDouble(bytes, coordOffset + 16, coordinate.getZ());
- break;
- case XYM:
- UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
- UNSAFE.putDouble(bytes, coordOffset + 16, coordinate.getM());
- break;
- case XYZM:
- UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
- UNSAFE.putDouble(bytes, coordOffset + 16, coordinate.getZ());
- UNSAFE.putDouble(bytes, coordOffset + 24, coordinate.getM());
- break;
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
- }
+ @Override
+ public void putCoordinate(int offset, Coordinate coordinate) {
+ long coordOffset = baseOffset + offset;
+ assert coordOffset + coordinateType.bytes <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ switch (coordinateType) {
+ case XY:
+ UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
+ break;
+ case XYZ:
+ UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
+ UNSAFE.putDouble(bytes, coordOffset + 16, coordinate.getZ());
+ break;
+ case XYM:
+ UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
+ UNSAFE.putDouble(bytes, coordOffset + 16, coordinate.getM());
+ break;
+ case XYZM:
+ UNSAFE.putDouble(bytes, coordOffset, coordinate.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coordinate.y);
+ UNSAFE.putDouble(bytes, coordOffset + 16, coordinate.getZ());
+ UNSAFE.putDouble(bytes, coordOffset + 24, coordinate.getM());
+ break;
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ }
- @Override
- public CoordinateSequence getCoordinate(int offset) {
- long coordOffset = baseOffset + offset;
- assert coordOffset + coordinateType.bytes <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- double x = UNSAFE.getDouble(bytes, coordOffset);
- double y = UNSAFE.getDouble(bytes, coordOffset + 8);
- double z;
- double m;
- Coordinate[] coordinates = new Coordinate[1];
- switch (coordinateType) {
- case XY:
- coordinates[0] = new CoordinateXY(x, y);
- return new CoordinateArraySequence(coordinates, 2, 0);
- case XYZ:
- z = UNSAFE.getDouble(bytes, coordOffset + 16);
- coordinates[0] = new Coordinate(x, y, z);
- return new CoordinateArraySequence(coordinates, 3, 0);
- case XYM:
- m = UNSAFE.getDouble(bytes, coordOffset + 16);
- coordinates[0] = new CoordinateXYM(x, y, m);
- return new CoordinateArraySequence(coordinates, 3, 1);
- case XYZM:
- z = UNSAFE.getDouble(bytes, coordOffset + 16);
- m = UNSAFE.getDouble(bytes, coordOffset + 24);
- coordinates[0] = new CoordinateXYZM(x, y, z, m);
- return new CoordinateArraySequence(coordinates, 4, 1);
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
- }
+ @Override
+ public CoordinateSequence getCoordinate(int offset) {
+ long coordOffset = baseOffset + offset;
+ assert coordOffset + coordinateType.bytes <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ double x = UNSAFE.getDouble(bytes, coordOffset);
+ double y = UNSAFE.getDouble(bytes, coordOffset + 8);
+ double z;
+ double m;
+ Coordinate[] coordinates = new Coordinate[1];
+ switch (coordinateType) {
+ case XY:
+ coordinates[0] = new CoordinateXY(x, y);
+ return new CoordinateArraySequence(coordinates, 2, 0);
+ case XYZ:
+ z = UNSAFE.getDouble(bytes, coordOffset + 16);
+ coordinates[0] = new Coordinate(x, y, z);
+ return new CoordinateArraySequence(coordinates, 3, 0);
+ case XYM:
+ m = UNSAFE.getDouble(bytes, coordOffset + 16);
+ coordinates[0] = new CoordinateXYM(x, y, m);
+ return new CoordinateArraySequence(coordinates, 3, 1);
+ case XYZM:
+ z = UNSAFE.getDouble(bytes, coordOffset + 16);
+ m = UNSAFE.getDouble(bytes, coordOffset + 24);
+ coordinates[0] = new CoordinateXYZM(x, y, z, m);
+ return new CoordinateArraySequence(coordinates, 4, 1);
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ }
- @Override
- public void putCoordinates(int offset, CoordinateSequence coordinates) {
- long coordOffset = baseOffset + offset;
- int numCoordinates = coordinates.size();
- assert coordOffset + (long) coordinateType.bytes * numCoordinates
- <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- switch (coordinateType) {
- case XY:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- UNSAFE.putDouble(bytes, coordOffset, coord.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
- coordOffset += 16;
- }
- break;
- case XYZ:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- UNSAFE.putDouble(bytes, coordOffset, coord.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
- UNSAFE.putDouble(bytes, coordOffset + 16, coord.getZ());
- coordOffset += 24;
- }
- break;
- case XYM:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- UNSAFE.putDouble(bytes, coordOffset, coord.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
- UNSAFE.putDouble(bytes, coordOffset + 16, coord.getM());
- coordOffset += 24;
- }
- break;
- case XYZM:
- for (int k = 0; k < numCoordinates; k++) {
- Coordinate coord = coordinates.getCoordinate(k);
- UNSAFE.putDouble(bytes, coordOffset, coord.x);
- UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
- UNSAFE.putDouble(bytes, coordOffset + 16, coord.getZ());
- UNSAFE.putDouble(bytes, coordOffset + 24, coord.getM());
- coordOffset += 32;
- }
- break;
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
+ @Override
+ public void putCoordinates(int offset, CoordinateSequence coordinates) {
+ long coordOffset = baseOffset + offset;
+ int numCoordinates = coordinates.size();
+ assert coordOffset + (long) coordinateType.bytes * numCoordinates
+ <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ switch (coordinateType) {
+ case XY:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ UNSAFE.putDouble(bytes, coordOffset, coord.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
+ coordOffset += 16;
+ }
+ break;
+ case XYZ:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ UNSAFE.putDouble(bytes, coordOffset, coord.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
+ UNSAFE.putDouble(bytes, coordOffset + 16, coord.getZ());
+ coordOffset += 24;
}
+ break;
+ case XYM:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ UNSAFE.putDouble(bytes, coordOffset, coord.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
+ UNSAFE.putDouble(bytes, coordOffset + 16, coord.getM());
+ coordOffset += 24;
+ }
+ break;
+ case XYZM:
+ for (int k = 0; k < numCoordinates; k++) {
+ Coordinate coord = coordinates.getCoordinate(k);
+ UNSAFE.putDouble(bytes, coordOffset, coord.x);
+ UNSAFE.putDouble(bytes, coordOffset + 8, coord.y);
+ UNSAFE.putDouble(bytes, coordOffset + 16, coord.getZ());
+ UNSAFE.putDouble(bytes, coordOffset + 24, coord.getM());
+ coordOffset += 32;
+ }
+ break;
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ }
- @Override
- public CoordinateSequence getCoordinates(int offset, int numCoordinates) {
- long coordOffset = baseOffset + offset;
- assert coordOffset + (long) coordinateType.bytes * numCoordinates
- <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- Coordinate[] coordinates = new Coordinate[numCoordinates];
- int dimension = 2;
- int measures = 0;
- switch (coordinateType) {
- case XY:
- for (int k = 0; k < numCoordinates; k++) {
- double x = UNSAFE.getDouble(bytes, coordOffset);
- double y = UNSAFE.getDouble(bytes, coordOffset + 8);
- coordinates[k] = new CoordinateXY(x, y);
- coordOffset += 16;
- }
- break;
- case XYZ:
- dimension = 3;
- for (int k = 0; k < numCoordinates; k++) {
- double x = UNSAFE.getDouble(bytes, coordOffset);
- double y = UNSAFE.getDouble(bytes, coordOffset + 8);
- double z = UNSAFE.getDouble(bytes, coordOffset + 16);
- coordinates[k] = new Coordinate(x, y, z);
- coordOffset += 24;
- }
- break;
- case XYM:
- dimension = 3;
- measures = 1;
- for (int k = 0; k < numCoordinates; k++) {
- double x = UNSAFE.getDouble(bytes, coordOffset);
- double y = UNSAFE.getDouble(bytes, coordOffset + 8);
- double m = UNSAFE.getDouble(bytes, coordOffset + 16);
- coordinates[k] = new CoordinateXYM(x, y, m);
- coordOffset += 24;
- }
- break;
- case XYZM:
- dimension = 4;
- measures = 1;
- for (int k = 0; k < numCoordinates; k++) {
- double x = UNSAFE.getDouble(bytes, coordOffset);
- double y = UNSAFE.getDouble(bytes, coordOffset + 8);
- double z = UNSAFE.getDouble(bytes, coordOffset + 16);
- double m = UNSAFE.getDouble(bytes, coordOffset + 24);
- coordinates[k] = new CoordinateXYZM(x, y, z, m);
- coordOffset += 32;
- }
- break;
- default:
- throw new IllegalStateException("coordinateType was not configured properly");
+ @Override
+ public CoordinateSequence getCoordinates(int offset, int numCoordinates) {
+ long coordOffset = baseOffset + offset;
+ assert coordOffset + (long) coordinateType.bytes * numCoordinates
+ <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ Coordinate[] coordinates = new Coordinate[numCoordinates];
+ int dimension = 2;
+ int measures = 0;
+ switch (coordinateType) {
+ case XY:
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = UNSAFE.getDouble(bytes, coordOffset);
+ double y = UNSAFE.getDouble(bytes, coordOffset + 8);
+ coordinates[k] = new CoordinateXY(x, y);
+ coordOffset += 16;
+ }
+ break;
+ case XYZ:
+ dimension = 3;
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = UNSAFE.getDouble(bytes, coordOffset);
+ double y = UNSAFE.getDouble(bytes, coordOffset + 8);
+ double z = UNSAFE.getDouble(bytes, coordOffset + 16);
+ coordinates[k] = new Coordinate(x, y, z);
+ coordOffset += 24;
+ }
+ break;
+ case XYM:
+ dimension = 3;
+ measures = 1;
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = UNSAFE.getDouble(bytes, coordOffset);
+ double y = UNSAFE.getDouble(bytes, coordOffset + 8);
+ double m = UNSAFE.getDouble(bytes, coordOffset + 16);
+ coordinates[k] = new CoordinateXYM(x, y, m);
+ coordOffset += 24;
}
- return new CoordinateArraySequence(coordinates, dimension, measures);
+ break;
+ case XYZM:
+ dimension = 4;
+ measures = 1;
+ for (int k = 0; k < numCoordinates; k++) {
+ double x = UNSAFE.getDouble(bytes, coordOffset);
+ double y = UNSAFE.getDouble(bytes, coordOffset + 8);
+ double z = UNSAFE.getDouble(bytes, coordOffset + 16);
+ double m = UNSAFE.getDouble(bytes, coordOffset + 24);
+ coordinates[k] = new CoordinateXYZM(x, y, z, m);
+ coordOffset += 32;
+ }
+ break;
+ default:
+ throw new IllegalStateException("coordinateType was not configured properly");
}
+ return new CoordinateArraySequence(coordinates, dimension, measures);
+ }
- @Override
- public GeometryBuffer slice(int offset) {
- assert baseOffset + offset <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
- int bytesOffset = (int) (baseOffset + offset - BYTE_ARRAY_BASE_OFFSET);
- return new UnsafeGeometryBuffer(bytes, bytesOffset);
- }
+ @Override
+ public GeometryBuffer slice(int offset) {
+ assert baseOffset + offset <= bytes.length + BYTE_ARRAY_BASE_OFFSET;
+ int bytesOffset = (int) (baseOffset + offset - BYTE_ARRAY_BASE_OFFSET);
+ return new UnsafeGeometryBuffer(bytes, bytesOffset);
+ }
- @Override
- public byte[] toByteArray() {
- if (baseOffset == BYTE_ARRAY_BASE_OFFSET) {
- return bytes;
- } else {
- int length = (int) (bytes.length - baseOffset + BYTE_ARRAY_BASE_OFFSET);
- byte[] copy = new byte[(int) length];
- UNSAFE.copyMemory(this.bytes, baseOffset, copy, BYTE_ARRAY_BASE_OFFSET, length);
- return copy;
- }
+ @Override
+ public byte[] toByteArray() {
+ if (baseOffset == BYTE_ARRAY_BASE_OFFSET) {
+ return bytes;
+ } else {
+ int length = (int) (bytes.length - baseOffset + BYTE_ARRAY_BASE_OFFSET);
+ byte[] copy = new byte[(int) length];
+ UNSAFE.copyMemory(this.bytes, baseOffset, copy, BYTE_ARRAY_BASE_OFFSET, length);
+ return copy;
}
+ }
}
diff --git a/common/src/main/java/org/apache/sedona/common/raster/DeepCopiedRenderedImage.java b/common/src/main/java/org/apache/sedona/common/raster/DeepCopiedRenderedImage.java
index 0df154076..e6ed87269 100644
--- a/common/src/main/java/org/apache/sedona/common/raster/DeepCopiedRenderedImage.java
+++ b/common/src/main/java/org/apache/sedona/common/raster/DeepCopiedRenderedImage.java
@@ -1,15 +1,20 @@
-/**
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sedona.common.raster;
@@ -21,18 +26,6 @@ import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.sun.media.jai.rmi.ColorModelState;
import com.sun.media.jai.util.ImageUtil;
import it.geosolutions.jaiext.range.NoDataContainer;
-import org.apache.sedona.common.raster.serde.AWTRasterSerializer;
-import org.apache.sedona.common.raster.serde.KryoUtil;
-import org.apache.sedona.common.utils.RasterUtils;
-
-import javax.media.jai.JAI;
-import javax.media.jai.PlanarImage;
-import javax.media.jai.RasterAccessor;
-import javax.media.jai.RasterFormatTag;
-import javax.media.jai.RemoteImage;
-import javax.media.jai.TileCache;
-import javax.media.jai.remote.SerializableState;
-import javax.media.jai.remote.SerializerFactory;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
@@ -49,443 +42,470 @@ import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
+import javax.media.jai.JAI;
+import javax.media.jai.PlanarImage;
+import javax.media.jai.RasterAccessor;
+import javax.media.jai.RasterFormatTag;
+import javax.media.jai.RemoteImage;
+import javax.media.jai.TileCache;
+import javax.media.jai.remote.SerializableState;
+import javax.media.jai.remote.SerializerFactory;
+import org.apache.sedona.common.raster.serde.AWTRasterSerializer;
+import org.apache.sedona.common.raster.serde.KryoUtil;
+import org.apache.sedona.common.utils.RasterUtils;
/**
- * This class is mostly copied from {@link javax.media.jai.remote.SerializableRenderedImage}. We've removed the
- * shallow copy support and fixed a bug of SerializableRenderedImage: When a deep-copied serializable rendered image
- * object is being disposed, it tries to connect to the remote server. However, there is no remote server in deep-copy
- * mode, so the dispose() method throws a java.net.SocketException.
+ * This class is mostly copied from {@link javax.media.jai.remote.SerializableRenderedImage}. We've
+ * removed the shallow copy support and fixed a bug of SerializableRenderedImage: When a deep-copied
+ * serializable rendered image object is being disposed, it tries to connect to the remote server.
+ * However, there is no remote server in deep-copy mode, so the dispose() method throws a
+ * java.net.SocketException.
*/
-public final class DeepCopiedRenderedImage implements RenderedImage, Serializable, KryoSerializable {
- private transient RenderedImage source;
- private int minX;
- private int minY;
- private int width;
- private int height;
- private int minTileX;
- private int minTileY;
- private int numXTiles;
- private int numYTiles;
- private int tileWidth;
- private int tileHeight;
- private int tileGridXOffset;
- private int tileGridYOffset;
- private transient SampleModel sampleModel;
- private transient ColorModel colorModel;
- private transient Vector<RenderedImage> sources;
- private transient Hashtable<String, Object> properties;
- private Rectangle imageBounds;
- private transient Raster imageRaster;
-
- public DeepCopiedRenderedImage() {
- this.sampleModel = null;
- this.colorModel = null;
- this.sources = null;
- this.properties = null;
- }
-
- public DeepCopiedRenderedImage(RenderedImage source) {
- this(source, true);
- }
-
- private DeepCopiedRenderedImage(RenderedImage source, boolean checkDataBuffer) {
- this.sampleModel = null;
- this.colorModel = null;
- this.sources = null;
- this.properties = null;
- if (source == null) {
- throw new IllegalArgumentException("source cannot be null");
- }
- SampleModel sm = source.getSampleModel();
- if (sm != null && SerializerFactory.getSerializer(sm.getClass()) == null) {
- throw new IllegalArgumentException("sample model object is not serializable");
+public final class DeepCopiedRenderedImage
+ implements RenderedImage, Serializable, KryoSerializable {
+ private transient RenderedImage source;
+ private int minX;
+ private int minY;
+ private int width;
+ private int height;
+ private int minTileX;
+ private int minTileY;
+ private int numXTiles;
+ private int numYTiles;
+ private int tileWidth;
+ private int tileHeight;
+ private int tileGridXOffset;
+ private int tileGridYOffset;
+ private transient SampleModel sampleModel;
+ private transient ColorModel colorModel;
+ private transient Vector<RenderedImage> sources;
+ private transient Hashtable<String, Object> properties;
+ private Rectangle imageBounds;
+ private transient Raster imageRaster;
+
+ public DeepCopiedRenderedImage() {
+ this.sampleModel = null;
+ this.colorModel = null;
+ this.sources = null;
+ this.properties = null;
+ }
+
+ public DeepCopiedRenderedImage(RenderedImage source) {
+ this(source, true);
+ }
+
+ private DeepCopiedRenderedImage(RenderedImage source, boolean checkDataBuffer) {
+ this.sampleModel = null;
+ this.colorModel = null;
+ this.sources = null;
+ this.properties = null;
+ if (source == null) {
+ throw new IllegalArgumentException("source cannot be null");
+ }
+ SampleModel sm = source.getSampleModel();
+ if (sm != null && SerializerFactory.getSerializer(sm.getClass()) == null) {
+ throw new IllegalArgumentException("sample model object is not serializable");
+ }
+ ColorModel cm = source.getColorModel();
+ if (cm != null && SerializerFactory.getSerializer(cm.getClass()) == null) {
+ throw new IllegalArgumentException("color model object is not serializable");
+ }
+ if (checkDataBuffer) {
+ Raster ras = source.getTile(source.getMinTileX(), source.getMinTileY());
+ if (ras != null) {
+ DataBuffer db = ras.getDataBuffer();
+ if (db != null && SerializerFactory.getSerializer(db.getClass()) == null) {
+ throw new IllegalArgumentException("data buffer object is not serializable");
}
- ColorModel cm = source.getColorModel();
- if (cm != null && SerializerFactory.getSerializer(cm.getClass()) == null) {
- throw new IllegalArgumentException("color model object is not serializable");
+ }
+ }
+
+ this.source = source;
+ if (source instanceof RemoteImage) {
+ throw new IllegalArgumentException("RemoteImage is not supported");
+ }
+ this.minX = source.getMinX();
+ this.minY = source.getMinY();
+ this.width = source.getWidth();
+ this.height = source.getHeight();
+ this.minTileX = source.getMinTileX();
+ this.minTileY = source.getMinTileY();
+ this.numXTiles = source.getNumXTiles();
+ this.numYTiles = source.getNumYTiles();
+ this.tileWidth = source.getTileWidth();
+ this.tileHeight = source.getTileHeight();
+ this.tileGridXOffset = source.getTileGridXOffset();
+ this.tileGridYOffset = source.getTileGridYOffset();
+ this.sampleModel = source.getSampleModel();
+ this.colorModel = source.getColorModel();
+ this.sources = new Vector<>();
+ this.sources.add(source);
+ this.properties = new Hashtable<>();
+ String[] propertyNames = source.getPropertyNames();
+ if (propertyNames != null) {
+ for (String propertyName : propertyNames) {
+ this.properties.put(propertyName, source.getProperty(propertyName));
+ }
+ }
+
+ this.imageBounds = new Rectangle(this.minX, this.minY, this.width, this.height);
+ }
+
+ @Override
+ public ColorModel getColorModel() {
+ return this.colorModel;
+ }
+
+ @Override
+ public Raster getData() {
+ if (source == null) {
+ return this.getData(this.imageBounds);
+ } else {
+ return this.source.getData();
+ }
+ }
+
+ @Override
+ public Raster getData(Rectangle rect) {
+ if (source == null) {
+ return this.imageRaster.createChild(
+ rect.x, rect.y, rect.width, rect.height, rect.x, rect.y, (int[]) null);
+ } else {
+ return this.source.getData(rect);
+ }
+ }
+
+ @Override
+ public WritableRaster copyData(WritableRaster dest) {
+ if (source == null) {
+ Rectangle region;
+ if (dest == null) {
+ region = this.imageBounds;
+ SampleModel destSM =
+ this.getSampleModel().createCompatibleSampleModel(region.width, region.height);
+ dest = Raster.createWritableRaster(destSM, new Point(region.x, region.y));
+ } else {
+ region = dest.getBounds().intersection(this.imageBounds);
+ }
+
+ if (!region.isEmpty()) {
+ int startTileX = PlanarImage.XToTileX(region.x, this.tileGridXOffset, this.tileWidth);
+ int startTileY = PlanarImage.YToTileY(region.y, this.tileGridYOffset, this.tileHeight);
+ int endTileX =
+ PlanarImage.XToTileX(region.x + region.width - 1, this.tileGridXOffset, this.tileWidth);
+ int endTileY =
+ PlanarImage.YToTileY(
+ region.y + region.height - 1, this.tileGridYOffset, this.tileHeight);
+ SampleModel[] sampleModels = new SampleModel[] {this.getSampleModel()};
+ int tagID = RasterAccessor.findCompatibleTag(sampleModels, dest.getSampleModel());
+ RasterFormatTag srcTag = new RasterFormatTag(this.getSampleModel(), tagID);
+ RasterFormatTag dstTag = new RasterFormatTag(dest.getSampleModel(), tagID);
+
+ for (int ty = startTileY; ty <= endTileY; ++ty) {
+ for (int tx = startTileX; tx <= endTileX; ++tx) {
+ Raster tile = this.getTile(tx, ty);
+ Rectangle subRegion = region.intersection(tile.getBounds());
+ RasterAccessor s = new RasterAccessor(tile, subRegion, srcTag, this.getColorModel());
+ RasterAccessor d = new RasterAccessor(dest, subRegion, dstTag, null);
+ ImageUtil.copyRaster(s, d);
+ }
}
- if (checkDataBuffer) {
- Raster ras = source.getTile(source.getMinTileX(), source.getMinTileY());
- if (ras != null) {
- DataBuffer db = ras.getDataBuffer();
- if (db != null && SerializerFactory.getSerializer(db.getClass()) == null) {
- throw new IllegalArgumentException("data buffer object is not serializable");
- }
- }
+ }
+
+ return dest;
+ } else {
+ return this.source.copyData(dest);
+ }
+ }
+
+ @Override
+ public int getHeight() {
+ return this.height;
+ }
+
+ @Override
+ public int getMinTileX() {
+ return this.minTileX;
+ }
+
+ @Override
+ public int getMinTileY() {
+ return this.minTileY;
+ }
+
+ @Override
+ public int getMinX() {
+ return this.minX;
+ }
+
+ @Override
+ public int getMinY() {
+ return this.minY;
+ }
+
+ @Override
+ public int getNumXTiles() {
+ return this.numXTiles;
+ }
+
+ @Override
+ public int getNumYTiles() {
+ return this.numYTiles;
+ }
+
+ @Override
+ public Object getProperty(String name) {
+ Object property = this.properties.get(name);
+ return property == null ? Image.UndefinedProperty : property;
+ }
+
+ @Override
+ public String[] getPropertyNames() {
+ String[] names = null;
+ if (!this.properties.isEmpty()) {
+ names = new String[this.properties.size()];
+ Enumeration<String> keys = this.properties.keys();
+ int index = 0;
+ while (keys.hasMoreElements()) {
+ names[index++] = keys.nextElement();
+ }
+ }
+
+ return names;
+ }
+
+ @Override
+ public SampleModel getSampleModel() {
+ return this.sampleModel;
+ }
+
+ @Override
+ public Vector<RenderedImage> getSources() {
+ return this.sources;
+ }
+
+ @Override
+ public Raster getTile(int tileX, int tileY) {
+ if (source == null) {
+ TileCache cache = JAI.getDefaultInstance().getTileCache();
+ if (cache != null) {
+ Raster tile = cache.getTile(this, tileX, tileY);
+ if (tile != null) {
+ return tile;
}
-
- this.source = source;
- if (source instanceof RemoteImage) {
- throw new IllegalArgumentException("RemoteImage is not supported");
- }
- this.minX = source.getMinX();
- this.minY = source.getMinY();
- this.width = source.getWidth();
- this.height = source.getHeight();
- this.minTileX = source.getMinTileX();
- this.minTileY = source.getMinTileY();
- this.numXTiles = source.getNumXTiles();
- this.numYTiles = source.getNumYTiles();
- this.tileWidth = source.getTileWidth();
- this.tileHeight = source.getTileHeight();
- this.tileGridXOffset = source.getTileGridXOffset();
- this.tileGridYOffset = source.getTileGridYOffset();
- this.sampleModel = source.getSampleModel();
- this.colorModel = source.getColorModel();
- this.sources = new Vector<>();
- this.sources.add(source);
- this.properties = new Hashtable<>();
- String[] propertyNames = source.getPropertyNames();
- if (propertyNames != null) {
- for (String propertyName : propertyNames) {
- this.properties.put(propertyName, source.getProperty(propertyName));
- }
+ }
+
+ Rectangle imageBounds =
+ new Rectangle(this.getMinX(), this.getMinY(), this.getWidth(), this.getHeight());
+ Rectangle destRect =
+ imageBounds.intersection(
+ new Rectangle(
+ this.tileXToX(tileX),
+ this.tileYToY(tileY),
+ this.getTileWidth(),
+ this.getTileHeight()));
+ Raster tile = this.getData(destRect);
+ if (cache != null) {
+ cache.add(this, tileX, tileY, tile);
+ }
+
+ return tile;
+ } else {
+ return this.source.getTile(tileX, tileY);
+ }
+ }
+
+ private int tileXToX(int tx) {
+ return PlanarImage.tileXToX(tx, this.getTileGridXOffset(), this.getTileWidth());
+ }
+
+ private int tileYToY(int ty) {
+ return PlanarImage.tileYToY(ty, this.getTileGridYOffset(), this.getTileHeight());
+ }
+
+ @Override
+ public int getTileGridXOffset() {
+ return this.tileGridXOffset;
+ }
+
+ @Override
+ public int getTileGridYOffset() {
+ return this.tileGridYOffset;
+ }
+
+ @Override
+ public int getTileHeight() {
+ return this.tileHeight;
+ }
+
+ @Override
+ public int getTileWidth() {
+ return this.tileWidth;
+ }
+
+ @Override
+ public int getWidth() {
+ return this.width;
+ }
+
+ private void writeObject(ObjectOutputStream out) throws IOException {
+ out.defaultWriteObject();
+
+ Hashtable<String, Object> propertyTable = getSerializableProperties();
+ out.writeObject(SerializerFactory.getState(this.colorModel, null));
+ out.writeObject(propertyTable);
+ if (this.source != null) {
+ Raster serializedRaster = RasterUtils.getRaster(this.source);
+ out.writeObject(SerializerFactory.getState(serializedRaster, null));
+ } else {
+ out.writeObject(SerializerFactory.getState(imageRaster, null));
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ this.source = null;
+ in.defaultReadObject();
+
+ SerializableState cmState = (SerializableState) in.readObject();
+ this.colorModel = (ColorModel) cmState.getObject();
+ this.properties = (Hashtable<String, Object>) in.readObject();
+ for (String key : this.properties.keySet()) {
+ Object value = this.properties.get(key);
+ // Restore the value of GC_NODATA property as a NoDataContainer object.
+ if (value instanceof SingleValueNoDataContainer) {
+ SingleValueNoDataContainer noDataContainer = (SingleValueNoDataContainer) value;
+ this.properties.put(key, new NoDataContainer(noDataContainer.singleValue));
+ }
+ }
+ SerializableState rasState = (SerializableState) in.readObject();
+ this.imageRaster = (Raster) rasState.getObject();
+
+ // The deserialized rendered image contains only one tile (imageRaster). We need to update
+ // the sample model and tile properties to reflect this.
+ this.sampleModel = this.imageRaster.getSampleModel();
+ this.tileWidth = this.width;
+ this.tileHeight = this.height;
+ this.numXTiles = 1;
+ this.numYTiles = 1;
+ this.minTileX = 0;
+ this.minTileY = 0;
+ this.tileGridXOffset = minX;
+ this.tileGridYOffset = minY;
... 152589 lines suppressed ...