diff --git a/README.md b/README.md index fd963f3bf..707dde074 100755 --- a/README.md +++ b/README.md @@ -359,6 +359,7 @@ The Neo4j Spatial Plugin is available for inclusion in the server version of Neo * [v0.27.2 for Neo4j 4.2.3](https://github.com/neo4j-contrib/m2/blob/master/releases/org/neo4j/neo4j-spatial/0.27.2-neo4j-4.2.3/neo4j-spatial-0.27.2-neo4j-4.2.3-server-plugin.jar?raw=true) * [v0.28.0 for Neo4j 4.2.3](https://github.com/neo4j-contrib/m2/blob/master/releases/org/neo4j/neo4j-spatial/0.28.0-neo4j-4.2.3/neo4j-spatial-0.28.0-neo4j-4.2.3-server-plugin.jar?raw=true) * [v0.28.1 for Neo4j 4.3.10](https://github.com/neo4j-contrib/m2/blob/master/releases/org/neo4j/neo4j-spatial/0.28.1-neo4j-4.3.10/neo4j-spatial-0.28.1-neo4j-4.3.10-server-plugin.jar?raw=true) + * [v0.28.1 for Neo4j 4.4.3](https://github.com/neo4j-contrib/m2/blob/master/releases/org/neo4j/neo4j-spatial/0.28.1-neo4j-4.4.3/neo4j-spatial-0.28.1-neo4j-4.4.3-server-plugin.jar?raw=true) For versions up to 0.15-neo4j-2.3.4: @@ -475,7 +476,7 @@ Add the following repositories and dependency to your project's pom.xml: org.neo4j neo4j-spatial - 0.28.1-neo4j-4.3.10 + 0.28.1-neo4j-4.4.3 ~~~ diff --git a/pom.xml b/pom.xml index 2f5bc1780..0fabe098b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,29 +1,33 @@ - 4.3.10 - 8.2.0 + 4.4.3 + 8.4.1 11 - 3.1 + 3.8.1 1.4 - 2.6 - 2.5.4 + 3.1.0 + 3.3.0 org.neo4j.maven.skins default-skin 2 - 24.2 + 26.2 20100819 20100819 - org.neo4j.gis UTF-8 + org.neo4j.gis github + 5.7.2 + 1.6.2 + 2.22.2 + 2.2.1 4.0.0 neo4j-spatial org.neo4j - 0.28.1-neo4j-4.3.10 + 0.28.1-neo4j-4.4.3 Neo4j - Spatial Components Spatial utilities and components for Neo4j http://components.neo4j.org/${project.artifactId}/${project.version} @@ -151,7 +155,7 @@ maven-surefire-plugin - 2.18.1 + ${maven-surefire-plugin.version} 1 1 @@ -162,7 +166,7 @@ org.asciidoctor asciidoctor-maven-plugin - 1.5.3 + ${asciidoctor.maven.plugin.version} generate-docs @@ -217,7 +221,7 @@ org.asciidoctor asciidoctorj-diagram - 1.3.1 + 2.2.1 @@ -317,6 +321,12 @@ ${neo4j.version} provided + + org.neo4j + neo4j-data-collector + ${neo4j.version} + provided + org.neo4j.app neo4j-server @@ -357,12 +367,29 @@ - junit - junit - 4.12 + org.junit.vintage + junit-vintage-engine + ${junit.version} test + org.junit.platform + junit-platform-launcher + ${junit.platform.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit.version} + test + org.hamcrest hamcrest-core 1.3 @@ -496,7 +523,7 @@ org.neo4j.build.plugins neo4j-doctools - 14 + 33 provided @@ -693,7 +720,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18.1 + ${maven-surefire-plugin.version} -server -Xms512m -Xmx2G -XX:+UseConcMarkSweepGC -Djava.awt.headless=true diff --git a/src/main/java/org/geotools/data/neo4j/Neo4jSpatialDataStoreFactory.java b/src/main/java/org/geotools/data/neo4j/Neo4jSpatialDataStoreFactory.java index 2977535ce..2d210ae89 100644 --- a/src/main/java/org/geotools/data/neo4j/Neo4jSpatialDataStoreFactory.java +++ b/src/main/java/org/geotools/data/neo4j/Neo4jSpatialDataStoreFactory.java @@ -63,7 +63,7 @@ public boolean canProcess(Map params) { } @Override - public DataStore createDataStore(Map params) throws IOException { + public DataStore createDataStore(Map params) throws IOException { if (!canProcess(params)) { throw new IOException("The parameters map isn't correct!!"); diff --git a/src/main/java/org/neo4j/gis/spatial/index/IndexManager.java b/src/main/java/org/neo4j/gis/spatial/index/IndexManager.java index 0e12f4e37..1d567c621 100644 --- a/src/main/java/org/neo4j/gis/spatial/index/IndexManager.java +++ b/src/main/java/org/neo4j/gis/spatial/index/IndexManager.java @@ -3,6 +3,7 @@ import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.schema.IndexDefinition; +import org.neo4j.internal.kernel.api.security.PermissionState; import org.neo4j.internal.kernel.api.security.PrivilegeAction; import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.kernel.api.KernelTransaction; @@ -27,8 +28,8 @@ private IndexAccessMode(SecurityContext securityContext) { } @Override - public boolean allowsTokenCreates(PrivilegeAction action) { - return true; + public PermissionState allowsTokenCreates(PrivilegeAction action) { + return PermissionState.EXPLICIT_GRANT; } @Override @@ -37,8 +38,8 @@ public boolean allowsSchemaWrites() { } @Override - public boolean allowsSchemaWrites(PrivilegeAction action) { - return true; + public PermissionState allowsSchemaWrites(PrivilegeAction action) { + return PermissionState.EXPLICIT_GRANT; } } diff --git a/src/main/java/org/neo4j/gis/spatial/index/LayerSpaceFillingCurvePointIndex.java b/src/main/java/org/neo4j/gis/spatial/index/LayerSpaceFillingCurvePointIndex.java index 206889c0a..b89ab7328 100644 --- a/src/main/java/org/neo4j/gis/spatial/index/LayerSpaceFillingCurvePointIndex.java +++ b/src/main/java/org/neo4j/gis/spatial/index/LayerSpaceFillingCurvePointIndex.java @@ -34,7 +34,7 @@ import org.neo4j.internal.kernel.api.*; import org.neo4j.internal.schema.IndexDescriptor; import org.neo4j.internal.schema.IndexType; -import org.neo4j.internal.schema.SchemaDescriptor; +import org.neo4j.internal.schema.SchemaDescriptors; import org.neo4j.io.pagecache.context.CursorContext; import org.neo4j.kernel.api.KernelTransaction; import org.neo4j.kernel.impl.core.NodeEntity; @@ -127,34 +127,28 @@ public Iterator search(KernelTransaction ktx, Label label, String property return Iterators.concat(results.iterator()); } - private ResourceIterator nodesByLabelAndProperty(KernelTransaction transaction, int labelId, PropertyIndexQuery query ) - { + private ResourceIterator nodesByLabelAndProperty(KernelTransaction transaction, int labelId, PropertyIndexQuery query) { Read read = transaction.dataRead(); - if ( query.propertyKeyId() == TokenRead.NO_TOKEN || labelId == TokenRead.NO_TOKEN ) - { + if (query.propertyKeyId() == TokenRead.NO_TOKEN || labelId == TokenRead.NO_TOKEN) { return emptyResourceIterator(); } - Iterator iterator = transaction.schemaRead().index( SchemaDescriptor.forLabel( labelId, query.propertyKeyId() ) ); - while ( iterator.hasNext() ) - { + Iterator iterator = transaction.schemaRead().index(SchemaDescriptors.forLabel(labelId, query.propertyKeyId())); + while (iterator.hasNext()) { IndexDescriptor index = iterator.next(); - if ( index.getIndexType() != IndexType.BTREE ) - { + // TODO: Do we need to support the new IndexType.RANGE index in Neo4j 4.4? + if (index.getIndexType() != IndexType.BTREE) { // Skip special indexes, such as the full-text indexes, because they can't handle all the queries we might throw at them. continue; } // Ha! We found an index - let's use it to find matching nodes - try - { + try { NodeValueIndexCursor cursor = transaction.cursors().allocateNodeValueIndexCursor(CursorContext.NULL, EmptyMemoryTracker.INSTANCE); - IndexReadSession indexSession = read.indexReadSession( index ); - read.nodeIndexSeek( indexSession, cursor, IndexQueryConstraints.unordered(false), query ); + IndexReadSession indexSession = read.indexReadSession(index); + read.nodeIndexSeek(transaction.queryContext(), indexSession, cursor, IndexQueryConstraints.unordered(false), query); return new CursorIterator<>(cursor, NodeIndexCursor::nodeReference, (c) -> new NodeEntity(transaction.internalTransaction(), c.nodeReference()), EMPTY_RESOURCE_TRACKER); - } - catch ( KernelException e ) - { + } catch (KernelException e) { // weird at this point but ignore and fallback to a label scan } } diff --git a/src/main/resources/META-INF/services/org.neo4j.server.plugins.ServerPlugin b/src/main/resources/META-INF/services/org.neo4j.server.plugins.ServerPlugin deleted file mode 100644 index 8240d522f..000000000 --- a/src/main/resources/META-INF/services/org.neo4j.server.plugins.ServerPlugin +++ /dev/null @@ -1 +0,0 @@ -org.neo4j.gis.spatial.server.plugin.SpatialPlugin \ No newline at end of file diff --git a/src/test/java/org/neo4j/gis/spatial/AbstractJavaDocTestBase.java b/src/test/java/org/neo4j/gis/spatial/AbstractJavaDocTestBase.java index 343d2b183..620afe55b 100644 --- a/src/test/java/org/neo4j/gis/spatial/AbstractJavaDocTestBase.java +++ b/src/test/java/org/neo4j/gis/spatial/AbstractJavaDocTestBase.java @@ -19,10 +19,10 @@ */ package org.neo4j.gis.spatial; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.doc.tools.JavaTestDocsGenerator; import org.neo4j.graphdb.GraphDatabaseService; @@ -38,19 +38,14 @@ * This class was copied from the class of the same name in neo4j-examples, in order to reduce the dependency chain */ public abstract class AbstractJavaDocTestBase implements GraphHolder { - @Rule - public TestData gen; - @Rule - public TestData> data; + @RegisterExtension + public TestData> data = TestData.producedThrough(GraphDescription.createGraphFor(this)); + @RegisterExtension + public TestData gen = TestData.producedThrough(JavaTestDocsGenerator.PRODUCER); protected static DatabaseManagementService databases; protected static GraphDatabaseService db; - public AbstractJavaDocTestBase() { - this.gen = TestData.producedThrough(JavaTestDocsGenerator.PRODUCER); - this.data = TestData.producedThrough(GraphDescription.createGraphFor(this)); - } - - @AfterClass + @AfterAll public static void shutdownDb() { try { if (databases != null) { @@ -67,14 +62,14 @@ public GraphDatabaseService graphdb() { return db; } - @Before + @BeforeEach public void setUp() { GraphDatabaseService graphdb = this.graphdb(); GraphDatabaseServiceCleaner.cleanDatabaseContent(graphdb); this.gen.get().setGraph(graphdb); } - @After + @AfterEach public void doc() { this.gen.get().document("target/docs/dev", "examples"); } diff --git a/src/test/java/org/neo4j/gis/spatial/LayerSignatureTest.java b/src/test/java/org/neo4j/gis/spatial/LayerSignatureTest.java index 915bb1eb9..7c7d23297 100644 --- a/src/test/java/org/neo4j/gis/spatial/LayerSignatureTest.java +++ b/src/test/java/org/neo4j/gis/spatial/LayerSignatureTest.java @@ -19,8 +19,8 @@ */ package org.neo4j.gis.spatial; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.graphdb.Transaction; import org.neo4j.internal.kernel.api.security.SecurityContext; @@ -29,12 +29,12 @@ import java.util.function.Consumer; import java.util.function.Function; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class LayerSignatureTest extends Neo4jTestCase implements Constants { private SpatialDatabaseService spatial; - @Before + @BeforeEach public void setup() throws Exception { super.setUp(); spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) graphDb(), SecurityContext.AUTH_DISABLED)); diff --git a/src/test/java/org/neo4j/gis/spatial/LayersTest.java b/src/test/java/org/neo4j/gis/spatial/LayersTest.java index 42e888781..04232cd65 100644 --- a/src/test/java/org/neo4j/gis/spatial/LayersTest.java +++ b/src/test/java/org/neo4j/gis/spatial/LayersTest.java @@ -19,13 +19,13 @@ */ package org.neo4j.gis.spatial; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.CoordinateList; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.LineString; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.exceptions.KernelException; import org.neo4j.gis.spatial.encoders.NativePointEncoder; @@ -54,21 +54,21 @@ import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; public class LayersTest { private DatabaseManagementService databases; private GraphDatabaseService graphDb; - @Before + @BeforeEach public void setup() throws KernelException { databases = new TestDatabaseManagementServiceBuilder(new File("target/layers").toPath()).impermanent().build(); graphDb = databases.database(DEFAULT_DATABASE_NAME); ((GraphDatabaseAPI) graphDb).getDependencyResolver().resolveDependency(GlobalProcedures.class).registerProcedure(SpatialProcedures.class); } - @After + @AfterEach public void teardown() { databases.shutdown(); } @@ -239,12 +239,12 @@ private String testSpecificEditableLayer(String layerName, Class { Layer layer = spatial.createLayer(tx, layerName, geometryEncoderClass, layerClass); assertNotNull(layer); - assertTrue("Should be an editable layer", layer instanceof EditableLayer); + assertTrue(layer instanceof EditableLayer, "Should be an editable layer"); }); inTx(tx -> { Layer layer = spatial.getLayer(tx, layerName); assertNotNull(layer); - assertTrue("Should be an editable layer", layer instanceof EditableLayer); + assertTrue(layer instanceof EditableLayer, "Should be an editable layer"); EditableLayer editableLayer = (EditableLayer) layer; CoordinateList coordinates = new CoordinateList(); diff --git a/src/test/java/org/neo4j/gis/spatial/Neo4jSpatialDataStoreTest.java b/src/test/java/org/neo4j/gis/spatial/Neo4jSpatialDataStoreTest.java index 6a2f31406..b0d4caddb 100644 --- a/src/test/java/org/neo4j/gis/spatial/Neo4jSpatialDataStoreTest.java +++ b/src/test/java/org/neo4j/gis/spatial/Neo4jSpatialDataStoreTest.java @@ -7,9 +7,10 @@ import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.crs.DefaultGeographicCRS; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.hamcrest.MatcherAssert; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.gis.spatial.osm.OSMImporter; import org.neo4j.graphdb.GraphDatabaseService; @@ -17,7 +18,6 @@ import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; -import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -26,7 +26,6 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; -import static org.junit.Assert.assertThat; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; public class Neo4jSpatialDataStoreTest { @@ -34,7 +33,7 @@ public class Neo4jSpatialDataStoreTest { private DatabaseManagementService databases; public GraphDatabaseService graph; - @Before + @BeforeEach public void setup() throws Exception { this.databases = new TestDatabaseManagementServiceBuilder(Path.of("target", "test")).impermanent().build(); this.graph = databases.database(DEFAULT_DATABASE_NAME); @@ -45,7 +44,7 @@ public void setup() throws Exception { importer.reIndex(graph); } - @After + @AfterEach public void teardown() { if (this.databases != null) { this.databases.shutdown(); @@ -58,7 +57,7 @@ public void teardown() { public void shouldOpenDataStore() { Neo4jSpatialDataStore store = new Neo4jSpatialDataStore(graph); ReferencedEnvelope bounds = store.getBounds("map"); - assertThat(bounds, equalTo(new ReferencedEnvelope(12.7856667, 13.2873561, 55.9254241, 56.2179056, DefaultGeographicCRS.WGS84))); + MatcherAssert.assertThat(bounds, equalTo(new ReferencedEnvelope(12.7856667, 13.2873561, 55.9254241, 56.2179056, DefaultGeographicCRS.WGS84))); } @Test @@ -70,7 +69,7 @@ public void shouldOpenDataStoreOnNonSpatialDatabase() { Neo4jSpatialDataStore store = new Neo4jSpatialDataStore(otherGraph); ReferencedEnvelope bounds = store.getBounds("map"); // TODO: rather should throw a descriptive exception - assertThat(bounds, equalTo(null)); + MatcherAssert.assertThat(bounds, equalTo(null)); } finally { if (otherDatabases != null) otherDatabases.shutdown(); @@ -81,16 +80,16 @@ public void shouldOpenDataStoreOnNonSpatialDatabase() { public void shouldBeAbleToListLayers() throws IOException { Neo4jSpatialDataStore store = new Neo4jSpatialDataStore(graph); String[] layers = store.getTypeNames(); - assertThat("Expected one layer", layers.length, equalTo(1)); - assertThat(layers[0], equalTo("map")); + MatcherAssert.assertThat("Expected one layer", layers.length, equalTo(1)); + MatcherAssert.assertThat(layers[0], equalTo("map")); } @Test public void shouldBeAbleToGetSchemaForLayer() throws IOException { Neo4jSpatialDataStore store = new Neo4jSpatialDataStore(graph); SimpleFeatureType schema = store.getSchema("map"); - assertThat("Expected 25 attributes", schema.getAttributeCount(), equalTo(25)); - assertThat("Expected geometry attribute to be called 'the_geom'", schema.getAttributeDescriptors().get(0).getLocalName(), equalTo("the_geom")); + MatcherAssert.assertThat("Expected 25 attributes", schema.getAttributeCount(), equalTo(25)); + MatcherAssert.assertThat("Expected geometry attribute to be called 'the_geom'", schema.getAttributeDescriptors().get(0).getLocalName(), equalTo("the_geom")); } @Test @@ -98,8 +97,8 @@ public void shouldBeAbleToGetFeatureSourceForLayer() throws IOException { Neo4jSpatialDataStore store = new Neo4jSpatialDataStore(graph); SimpleFeatureSource source = store.getFeatureSource("map"); SimpleFeatureCollection features = source.getFeatures(); - assertThat("Expected 217 features", features.size(), equalTo(217)); - assertThat("Expected there to be a feature with name 'Nybrodalsvägen'", featureNames(features), hasItem("Nybrodalsvägen")); + MatcherAssert.assertThat("Expected 217 features", features.size(), equalTo(217)); + MatcherAssert.assertThat("Expected there to be a feature with name 'Nybrodalsvägen'", featureNames(features), hasItem("Nybrodalsvägen")); } @Test @@ -108,10 +107,10 @@ public void shouldBeAbleToGetInfoForLayer() throws IOException { SimpleFeatureSource source = store.getFeatureSource("map"); ResourceInfo info = source.getInfo(); ReferencedEnvelope bounds = info.getBounds(); - assertThat(bounds, equalTo(new ReferencedEnvelope(12.7856667, 13.2873561, 55.9254241, 56.2179056, DefaultGeographicCRS.WGS84))); + MatcherAssert.assertThat(bounds, equalTo(new ReferencedEnvelope(12.7856667, 13.2873561, 55.9254241, 56.2179056, DefaultGeographicCRS.WGS84))); SimpleFeatureCollection features = source.getFeatures(); - assertThat("Expected 217 features", features.size(), equalTo(217)); - assertThat("Expected there to be a feature with name 'Nybrodalsvägen'", featureNames(features), hasItem("Nybrodalsvägen")); + MatcherAssert.assertThat("Expected 217 features", features.size(), equalTo(217)); + MatcherAssert.assertThat("Expected there to be a feature with name 'Nybrodalsvägen'", featureNames(features), hasItem("Nybrodalsvägen")); } private Set featureNames(SimpleFeatureCollection features) { diff --git a/src/test/java/org/neo4j/gis/spatial/Neo4jTestCase.java b/src/test/java/org/neo4j/gis/spatial/Neo4jTestCase.java index efba3b5aa..8b981d26f 100644 --- a/src/test/java/org/neo4j/gis/spatial/Neo4jTestCase.java +++ b/src/test/java/org/neo4j/gis/spatial/Neo4jTestCase.java @@ -19,9 +19,10 @@ */ package org.neo4j.gis.spatial; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.neo4j.configuration.Config; import org.neo4j.configuration.GraphDatabaseInternalSettings; import org.neo4j.configuration.GraphDatabaseSettings; @@ -34,7 +35,7 @@ import org.neo4j.kernel.api.procedure.GlobalProcedures; import org.neo4j.kernel.internal.GraphDatabaseAPI; import org.neo4j.test.TestDatabaseManagementServiceBuilder; -import org.neo4j.test.rule.fs.EphemeralFileSystemRule; +import org.neo4j.io.fs.EphemeralFileSystemAbstraction; import java.io.File; import java.io.IOException; @@ -79,7 +80,7 @@ public abstract class Neo4jTestCase { private long storePrefix; - @Before + @BeforeEach public void setUp() throws Exception { updateStorePrefix(); setUp(true); @@ -139,15 +140,20 @@ private Config makeConfig(Map config) { return builder.build(); } - @Rule - public EphemeralFileSystemRule fileSystemRule = new EphemeralFileSystemRule(); + private static EphemeralFileSystemAbstraction fileSystem; - @Before - public void before() throws Exception { - fileSystemRule.get().mkdirs(new File("target").toPath()); + @BeforeAll + static void beforeAll() throws IOException { + fileSystem = new EphemeralFileSystemAbstraction(); + fileSystem.mkdirs(new File("target").toPath()); } - @After + @AfterAll + static void afterAll() throws IOException { + fileSystem.close(); + } + + @AfterEach public void tearDown() { shutdownDatabase(true); } diff --git a/src/test/java/org/neo4j/gis/spatial/OsmAnalysisTest.java b/src/test/java/org/neo4j/gis/spatial/OsmAnalysisTest.java index f80544a70..e2cd78c59 100644 --- a/src/test/java/org/neo4j/gis/spatial/OsmAnalysisTest.java +++ b/src/test/java/org/neo4j/gis/spatial/OsmAnalysisTest.java @@ -19,13 +19,12 @@ */ package org.neo4j.gis.spatial; -import org.locationtech.jts.geom.Coordinate; -import org.apache.commons.io.FileUtils; import org.geotools.data.neo4j.StyledImageExporter; import org.geotools.geometry.jts.ReferencedEnvelope; -import org.junit.Test; -import org.junit.runners.Parameterized; -import org.neo4j.dbms.api.DatabaseManagementService; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.locationtech.jts.geom.Coordinate; import org.neo4j.gis.spatial.filter.SearchRecords; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.gis.spatial.osm.OSMDataset; @@ -34,34 +33,25 @@ import org.neo4j.gis.spatial.osm.OSMRelation; import org.neo4j.gis.spatial.rtree.Envelope; import org.neo4j.gis.spatial.rtree.filter.SearchAll; -import org.neo4j.gis.spatial.utilities.ReferenceNodes; -import org.neo4j.graphdb.*; +import org.neo4j.graphdb.Direction; +import org.neo4j.graphdb.Node; +import org.neo4j.graphdb.Relationship; +import org.neo4j.graphdb.Transaction; import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.kernel.internal.GraphDatabaseAPI; -import org.neo4j.test.TestDatabaseManagementServiceBuilder; import org.opengis.referencing.crs.CoordinateReferenceSystem; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Map.Entry; +import java.util.stream.Stream; -import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; - -public class OsmAnalysisTest extends TestOSMImport { +public class OsmAnalysisTest extends TestOSMImportBase { public static final String spatialTestMode = System.getProperty("spatial.test.mode"); public static final boolean usePoints = true; - private final int years; - private final int days; - - public OsmAnalysisTest(String layerName, int years, int days) { - super(layerName, true); - this.years = years; - this.days = days; - } - @Parameterized.Parameters(name = "{index}-{0}: years={1}, days={2}") - public static Collection parameters() { + private static Stream parameters() { deleteBaseDir(); String[] smallModels = new String[]{"one-street.osm", "two-street.osm"}; //String[] mediumModels = new String[]{"map.osm", "map2.osm"}; @@ -92,23 +82,24 @@ public static Collection parameters() { int[] days = new int[]{1}; // Finally build the set of complete test cases based on the collection above - ArrayList suite = new ArrayList<>(); + ArrayList params = new ArrayList<>(); for (final String layerName : layersToTest) { for (final int y : years) { for (final int d : days) { - suite.add(new Object[]{layerName, y, d}); + params.add(Arguments.of(layerName, y, d)); } } } - System.out.println("This suite has " + suite.size() + " tests"); - for (Object[] params : suite) { - System.out.println("\t" + Arrays.toString(params)); + System.out.println("This suite has " + params.size() + " tests"); + for (Arguments arguments : params) { + System.out.println("\t" + Arrays.toString(arguments.get())); } - return suite; + return params.stream(); } - @Test - public void runTest() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void runTest(String layerName, int years, int days) throws Exception { runAnalysis(layerName, years, days); } diff --git a/src/test/java/org/neo4j/gis/spatial/ProgressLoggingListenerTest.java b/src/test/java/org/neo4j/gis/spatial/ProgressLoggingListenerTest.java index b51b6a3a8..b1da009c0 100644 --- a/src/test/java/org/neo4j/gis/spatial/ProgressLoggingListenerTest.java +++ b/src/test/java/org/neo4j/gis/spatial/ProgressLoggingListenerTest.java @@ -19,7 +19,7 @@ */ package org.neo4j.gis.spatial; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.neo4j.gis.spatial.rtree.Listener; import org.neo4j.gis.spatial.rtree.ProgressLoggingListener; @@ -45,8 +45,11 @@ public void testProgressLoggingListnerWithOnlyStartAndEnd() { testProgressLoggingListenerWithSpecifiedWaits(unitsOfWork, timeWait, throttle, 3); } + @SuppressWarnings({"CatchMayIgnoreException", "RedundantStringFormatCall"}) private void testProgressLoggingListenerWithSpecifiedWaits(int unitsOfWork, long timeWait, long throttle, int expectedLogCount) { - PrintStream out = spy(System.out); + // When running maven-surefire System.out is replaced with a PrintStream that mockito cannot spy on, so we need to wrap it here + PrintStream wrapped = new PrintStream(System.out); + PrintStream out = spy(wrapped); Listener listener = new ProgressLoggingListener("test", out).setTimeWait(timeWait); listener.begin(unitsOfWork); for (int step = 0; step < unitsOfWork; step++) { diff --git a/src/test/java/org/neo4j/gis/spatial/TestDynamicLayers.java b/src/test/java/org/neo4j/gis/spatial/TestDynamicLayers.java index 6592015a7..75e97f364 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestDynamicLayers.java +++ b/src/test/java/org/neo4j/gis/spatial/TestDynamicLayers.java @@ -19,15 +19,15 @@ */ package org.neo4j.gis.spatial; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.LinearRing; -import org.locationtech.jts.geom.Polygon; import org.geotools.data.DataSourceException; import org.geotools.data.DataStore; import org.geotools.data.neo4j.Neo4jSpatialDataStore; import org.geotools.data.neo4j.StyledImageExporter; import org.geotools.data.simple.SimpleFeatureCollection; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.LinearRing; +import org.locationtech.jts.geom.Polygon; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.gis.spatial.osm.OSMImporter; import org.neo4j.gis.spatial.osm.OSMLayer; @@ -42,8 +42,8 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class TestDynamicLayers extends Neo4jTestCase implements Constants { @@ -62,6 +62,7 @@ public void testImageExport_HighwayShp() throws Exception { runDynamicShapefile("highway.shp"); } + @SuppressWarnings("SameParameterValue") private void runDynamicShapefile(String shpFile) throws Exception { printDatabaseStats(); loadTestShpData(shpFile); @@ -208,10 +209,11 @@ private void runShapefileExport(String osmFile) throws Exception { } } } - assertEquals("Mismatching number of data source exceptions and raw geometry layers", countMultiGeometryLayers, - countMultiGeometryExceptions); + assertEquals(countMultiGeometryLayers, countMultiGeometryExceptions, + "Mismatching number of data source exceptions and raw geometry layers"); } + @SuppressWarnings("SameParameterValue") private Envelope scale(Envelope bbox, double fraction) { double xoff = bbox.getWidth(0) * (1.0 - fraction) / 2.0; double yoff = bbox.getWidth(1) * (1.0 - fraction) / 2.0; @@ -244,8 +246,7 @@ private void checkIndexAndFeatureCount(Layer layer) throws IOException { try (Transaction tx = graphDb().beginTx()) { SimpleFeatureCollection features = store.getFeatureSource(layer.getName()).getFeatures(); System.out.println("Layer '" + layer.getName() + "' has " + features.size() + " features"); - assertEquals("FeatureCollection.size for layer '" + layer.getName() + "' not the same as index count", - layer.getIndex().count(tx), features.size()); + assertEquals(layer.getIndex().count(tx), features.size(), "FeatureCollection.size for layer '" + layer.getName() + "' not the same as index count"); tx.commit(); } } @@ -271,12 +272,12 @@ private Envelope checkLayer(String layerName) { try (Transaction tx = graphDb().beginTx()) { layer = spatial.getLayer(tx, layerName); } - assertNotNull("Layer index should not be null", layer.getIndex()); + assertNotNull(layer.getIndex(), "Layer index should not be null"); Envelope bbox; try (Transaction tx = graphDb().beginTx()) { bbox = layer.getIndex().getBoundingBox(tx); } - assertNotNull("Layer index envelope should not be null", bbox); + assertNotNull(bbox, "Layer index envelope should not be null"); System.out.println("Layer has bounding box: " + bbox); Neo4jTestUtils.debugIndexTree(graphDb(), layerName); return bbox; diff --git a/src/test/java/org/neo4j/gis/spatial/TestIntersectsPathQueries.java b/src/test/java/org/neo4j/gis/spatial/TestIntersectsPathQueries.java index c3cb14a9c..570e8c04a 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestIntersectsPathQueries.java +++ b/src/test/java/org/neo4j/gis/spatial/TestIntersectsPathQueries.java @@ -19,14 +19,13 @@ */ package org.neo4j.gis.spatial; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.impl.CoordinateArraySequence; -import org.locationtech.jts.io.ParseException; import org.locationtech.jts.simplify.TopologyPreservingSimplifier; -import org.junit.Test; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.dbms.api.DatabaseManagementServiceBuilder; import org.neo4j.gis.spatial.index.IndexManager; @@ -39,7 +38,6 @@ import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.kernel.internal.GraphDatabaseAPI; -import javax.xml.stream.XMLStreamException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -47,10 +45,9 @@ import java.nio.charset.StandardCharsets; import java.util.*; import java.util.Map.Entry; -import java.util.function.Consumer; import java.util.function.Function; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; public class TestIntersectsPathQueries { @@ -71,7 +68,7 @@ public class TestIntersectsPathQueries { * very large, and the set of test points quite large. */ @Test - public void testPointSetGeoptimaIntersection() throws ParseException, IOException, XMLStreamException, InterruptedException { + public void testPointSetGeoptimaIntersection() throws InterruptedException { String osmPath = "albert/osm/massachusetts.highway.osm"; String shpPath = "albert/shp/massachusetts_highway.shp"; String dbRoot = "target/geoptima"; @@ -145,7 +142,7 @@ private void importOSMDatabase(String osmPath, String dbRoot, String dbName, Str }); } - private class Performance { + private static class Performance { long start; long duration; String name; @@ -182,7 +179,7 @@ private double overlaps(Collection original) { } private double fractionOf(Collection subset, Collection set) { - HashSet all = new HashSet(set); + HashSet all = new HashSet<>(set); int count = 0; for (Node node : subset) { if (all.contains(node)) { @@ -201,6 +198,7 @@ public String toString() { } } + @SuppressWarnings("SameParameterValue") private void runTestPointSetGeoptimaIntersection(String tracePath, String dbRoot, String dbName, String layerName, boolean testMultiPoint) { withDatabase(dbRoot, dbName, Neo4jTestCase.NORMAL_CONFIG, graphDb -> { SpatialDatabaseService spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) graphDb, SecurityContext.AUTH_DISABLED)); @@ -217,8 +215,8 @@ private void runTestPointSetGeoptimaIntersection(String tracePath, String dbRoot } //OSMLayer layer = (OSMLayer) spatial.getOrCreateLayer(layerName, OSMGeometryEncoder.class, OSMLayer.class); Layer layer = spatial.getLayer(tx, layerName); - assertNotNull("Layer index should not be null", layer.getIndex()); - assertNotNull("Layer index envelope should not be null", layer.getIndex().getBoundingBox(tx)); + assertNotNull(layer.getIndex(), "Layer index should not be null"); + assertNotNull(layer.getIndex().getBoundingBox(tx), "Layer index envelope should not be null"); Envelope bbox = Utilities.fromNeo4jToJts(layer.getIndex().getBoundingBox(tx)); TestOSMImport.debugEnvelope(bbox, layerName, Constants.PROP_BBOX); indexCount = TestOSMImport.checkIndexCount(tx, layer); @@ -226,10 +224,10 @@ private void runTestPointSetGeoptimaIntersection(String tracePath, String dbRoot } TestOSMImport.checkFeatureCount(graphDb, indexCount, layerName); - HashMap performances = new LinkedHashMap(); + HashMap performances = new LinkedHashMap<>(); // Import the sample data of points on a path (drive test) - ArrayList coordinates = new ArrayList(); + ArrayList coordinates = new ArrayList<>(); BufferedReader locations = new BufferedReader(new FileReader(tracePath)); String line; Performance performance = new Performance("import"); @@ -247,7 +245,7 @@ private void runTestPointSetGeoptimaIntersection(String tracePath, String dbRoot // Slow Test, iterating over all Point objects double distanceInKm = 0.01; - HashSet results = new HashSet(); + HashSet results = new HashSet<>(); System.out.println("Searching for geometries near " + coordinates.size() + " locations: " + coordinates.get(0) + " ... " + coordinates.get(coordinates.size() - 1)); performance = new Performance("search points"); @@ -268,7 +266,7 @@ private void runTestPointSetGeoptimaIntersection(String tracePath, String dbRoot // Faster tests with LineString and MultiPoint GeometryFactory geometryFactory = new GeometryFactory(); CoordinateArraySequence cseq = new CoordinateArraySequence(coordinates.toArray(new Coordinate[0])); - HashMap testGeoms = new LinkedHashMap(); + HashMap testGeoms = new LinkedHashMap<>(); testGeoms.put("LineString", geometryFactory.createLineString(cseq)); testGeoms.put("LineString.buffer(0.001)", testGeoms.get("LineString").buffer(0.001)); testGeoms.put("LineString.buffer(0.0001)", testGeoms.get("LineString").buffer(0.0001)); @@ -327,6 +325,7 @@ private void printResults(Collection results) { } } + @SuppressWarnings("SameParameterValue") private List runSearch(GeoPipeline pipeline, boolean verbose) { List results = pipeline.toNodeList(); if (verbose) { @@ -336,7 +335,7 @@ private List runSearch(GeoPipeline pipeline, boolean verbose) { } private static void withDatabase(String dbRoot, String dbName, Map rawConfig, Function withDb) throws RuntimeException { - DatabaseManagementService databases = new DatabaseManagementServiceBuilder(new File(dbRoot, dbName)).setConfigRaw(rawConfig).build(); + DatabaseManagementService databases = new DatabaseManagementServiceBuilder(new File(dbRoot, dbName).toPath()).setConfigRaw(rawConfig).build(); try { GraphDatabaseService graphDb = databases.database(DEFAULT_DATABASE_NAME); Exception e = withDb.apply(graphDb); diff --git a/src/test/java/org/neo4j/gis/spatial/TestOSMImport.java b/src/test/java/org/neo4j/gis/spatial/TestOSMImport.java index a9c0ce4a5..636fe94ca 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestOSMImport.java +++ b/src/test/java/org/neo4j/gis/spatial/TestOSMImport.java @@ -19,42 +19,25 @@ */ package org.neo4j.gis.spatial; -import org.locationtech.jts.geom.Envelope; -import org.locationtech.jts.geom.Geometry; -import org.geotools.data.DataStore; -import org.geotools.data.neo4j.Neo4jSpatialDataStore; -import org.geotools.data.simple.SimpleFeatureCollection; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.neo4j.gis.spatial.index.IndexManager; -import org.neo4j.gis.spatial.osm.*; -import org.neo4j.gis.spatial.osm.OSMDataset.Way; -import org.neo4j.gis.spatial.pipes.osm.OSMGeoPipeline; -import org.neo4j.graphdb.*; -import org.neo4j.internal.kernel.api.security.SecurityContext; -import org.neo4j.kernel.internal.GraphDatabaseAPI; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.*; - -import static org.junit.Assert.*; - -@RunWith(Parameterized.class) -public class TestOSMImport extends Neo4jTestCase { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.neo4j.graphdb.Node; +import org.neo4j.graphdb.Relationship; +import org.neo4j.graphdb.RelationshipType; +import org.neo4j.graphdb.Transaction; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +public class TestOSMImport extends TestOSMImportBase { public static final String spatialTestMode = System.getProperty("spatial.test.mode"); - protected final String layerName; - private final boolean includePoints; - - public TestOSMImport(String layerName, boolean includePoints) { - this.layerName = layerName; - this.includePoints = includePoints; - } - @Parameterized.Parameters(name = "{index}-{0}: includePoints={1}") - public static Collection parameters() { + private static final Stream parameters() { deleteBaseDir(); String[] smallModels = new String[]{"one-street.osm", "two-street.osm"}; // String[] mediumModels = new String[] { "map.osm", "map2.osm" }; @@ -81,256 +64,68 @@ public static Collection parameters() { } boolean[] pointsTestModes = new boolean[]{true, false}; - // Finally build the set of complete test cases based on the collection above - ArrayList suite = new ArrayList<>(); + // Finally, build the set of complete test cases based on the collection above + ArrayList params = new ArrayList<>(); for (final String layerName : layersToTest) { for (final boolean includePoints : pointsTestModes) { - suite.add(new Object[]{layerName, includePoints}); + params.add(Arguments.of(layerName, includePoints)); } } - System.out.println("This suite has " + suite.size() + " tests"); - for (Object[] params : suite) { - System.out.println("\t" + Arrays.toString(params)); + System.out.println("This suite has " + params.size() + " tests"); + for (Arguments arguments : params) { + System.out.println("\t" + Arrays.toString(arguments.get())); } - return suite; + return params.stream(); } - @Test - public void runTest() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void runTest(String layerName, boolean includePoints) throws Exception { runImport(layerName, includePoints); - } - - protected static String checkOSMFile(String osm) { - File osmFile = new File(osm); - if (!osmFile.exists()) { - osmFile = new File(new File("osm"), osm); - if (!osmFile.exists()) { - return null; + try (Transaction tx = graphDb().beginTx()) { + for (Node n : tx.getAllNodes()) { + debugNode(n); } - } - return osmFile.getPath(); - } - - protected static void checkOSMLayer(GraphDatabaseService db, String layerName) throws IOException { - int indexCount; - try (Transaction tx = db.beginTx()) { - SpatialDatabaseService spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) db, SecurityContext.AUTH_DISABLED)); - OSMLayer layer = (OSMLayer) spatial.getOrCreateLayer(tx, layerName, OSMGeometryEncoder.class, OSMLayer.class); - assertNotNull("OSM Layer index should not be null", layer.getIndex()); - assertNotNull("OSM Layer index envelope should not be null", layer.getIndex().getBoundingBox(tx)); - Envelope bbox = Utilities.fromNeo4jToJts(layer.getIndex().getBoundingBox(tx)); - debugEnvelope(bbox, layerName, Constants.PROP_BBOX); - // ((RTreeIndex)layer.getIndex()).debugIndexTree(); - indexCount = checkIndexCount(tx, layer); - checkChangesetsAndUsers(tx, layer); - checkOSMSearch(tx, layer); tx.commit(); } - checkFeatureCount(db, indexCount, layerName); - } - - public static void checkOSMSearch(Transaction tx, OSMLayer layer) { - OSMDataset osm = OSMDataset.fromLayer(tx, layer); - Way way = null; - int count = 0; - for (Way wayNode : osm.getWays(tx)) { - // Do not `break` from the loop or experience the RelationshipTraversalCursor leak bug in Neo4j 4.3 - if (count++ <= 100) { - way = wayNode; - } - } - assertNotNull("Should be at least one way", way); - Envelope bbox = way.getEnvelope(); - runSearches(tx, layer, bbox, true); - org.neo4j.gis.spatial.rtree.Envelope layerBBox = layer.getIndex().getBoundingBox(tx); - double[] centre = layerBBox.centre(); - double width = layerBBox.getWidth(0) / 100.0; - double height = layerBBox.getWidth(1) / 100.0; - bbox = new Envelope(centre[0] - width, centre[0] + width, centre[1] - height, centre[1] + height); - runSearches(tx, layer, bbox, false); - } - - private static void runSearches(Transaction tx, OSMLayer layer, Envelope bbox, boolean willHaveResult) { - for (int i = 0; i < 4; i++) { - Geometry searchArea = layer.getGeometryFactory().toGeometry(bbox); - runWithinSearch(tx, layer, searchArea, willHaveResult); - bbox.expandBy(bbox.getWidth(), bbox.getHeight()); - } - } - - private static void runWithinSearch(Transaction tx, OSMLayer layer, Geometry searchArea, boolean willHaveResult) { - long start = System.currentTimeMillis(); - List results = OSMGeoPipeline.startWithinSearch(tx, layer, searchArea).toSpatialDatabaseRecordList(); - long time = System.currentTimeMillis() - start; - System.out.println("Took " + time + "ms to find " + results.size() + " search results in layer " + layer.getName() - + " using search within " + searchArea); - if (willHaveResult) - assertTrue("Should be at least one result, but got zero", results.size() > 0); - } - - public static void debugEnvelope(Envelope bbox, String layer, String name) { - System.out.println("Layer '" + layer + "' has envelope '" + name + "': " + bbox); - System.out.println("\tX: [" + bbox.getMinX() + ":" + bbox.getMaxX() + "]"); - System.out.println("\tY: [" + bbox.getMinY() + ":" + bbox.getMaxY() + "]"); - } - - public static int checkIndexCount(Transaction tx, Layer layer) { - if (layer.getIndex().count(tx) < 1) { - System.out.println("Warning: index count zero: " + layer.getName()); - } - System.out.println("Layer '" + layer.getName() + "' has " + layer.getIndex().count(tx) + " entries in the index"); - return layer.getIndex().count(tx); - } - - public static void checkFeatureCount(GraphDatabaseService db, int indexCount, String layerName) throws IOException { - DataStore store = new Neo4jSpatialDataStore(db); - SimpleFeatureCollection features = store.getFeatureSource(layerName).getFeatures(); - int featuresSize = features.size(); - System.out.println("Layer '" + layerName + "' has " + featuresSize + " features"); - assertEquals("FeatureCollection.size for layer '" + layerName + "' not the same as index count", indexCount, featuresSize); } - private static void checkChangesetsAndUsers(Transaction tx, OSMLayer layer) { - double totalMatch = 0.0; - int waysMatched = 0; - int waysCounted = 0; - int nodesCounted = 0; - int waysMissing = 0; - int nodesMissing = 0; - int usersMissing = 0; - float maxMatch = 0.0f; - float minMatch = 1.0f; - HashMap userNodeCount = new HashMap<>(); - HashMap userNames = new HashMap<>(); - HashMap userIds = new HashMap<>(); - OSMDataset dataset = OSMDataset.fromLayer(tx, layer); - for (Node way : dataset.getAllWayNodes(tx)) { - int node_count = 0; - int match_count = 0; - assertNull("Way has changeset property", way.getProperty("changeset", null)); - Node wayChangeset = dataset.getChangeset(way); - if (wayChangeset != null) { - long wayCS = (Long) wayChangeset.getProperty("changeset"); - for (Node node : dataset.getWayNodes(way)) { - assertNull("Node has changeset property", node.getProperty("changeset", null)); - Node nodeChangeset = dataset.getChangeset(node); - if (nodeChangeset == null) { - nodesMissing++; - } else { - long nodeCS = (Long) nodeChangeset.getProperty("changeset"); - if (nodeChangeset.equals(wayChangeset)) { - match_count++; - } else { - assertNotEquals("Two changeset nodes should not have the same changeset number: way(" + wayCS + ")==node(" + nodeCS + ")", wayCS, nodeCS); - } - Node user = dataset.getUser(nodeChangeset); - if (user != null) { - long userid = user.getId(); - if (userNodeCount.containsKey(userid)) { - userNodeCount.put(userid, userNodeCount.get(userid) + 1); - } else { - userNodeCount.put(userid, 1); - userNames.put(userid, (String) user.getProperty("name", null)); - userIds.put(userid, (Long) user.getProperty("uid", null)); - } - } else { - if (usersMissing++ < 10) { - System.out.println("Changeset " + nodeCS + " should have user: " + nodeChangeset); - } - } - } - node_count++; - } - } else { - waysMissing++; - } - if (node_count > 0) { - waysMatched++; - float match = ((float) match_count) / ((float) node_count); - maxMatch = Math.max(maxMatch, match); - minMatch = Math.min(minMatch, match); - totalMatch += match; - nodesCounted += node_count; - } - waysCounted++; - } - System.out.println("After checking " + waysCounted + " ways:"); - System.out.println("\twe found " + waysMatched + " ways with an average of " + (nodesCounted / waysMatched) + " nodes"); - System.out.println("\tand an average of " + (100.0 * totalMatch / waysMatched) + "% matching changesets"); - System.out.println("\twith min-match " + (100.0 * minMatch) + "% and max-match " + (100.0 * maxMatch) + "%"); - System.out.println("\tWays missing changsets: " + waysMissing); - System.out.println("\tNodes missing changsets: " + nodesMissing + " (~" + (nodesMissing / waysMatched) + " / way)"); - System.out.println("\tUnique users: " + userNodeCount.size() + " (with " + usersMissing + " changeset missing users)"); - ArrayList> userCounts = new ArrayList<>(); - for (long user : userNodeCount.keySet()) { - int count = userNodeCount.get(user); - userCounts.ensureCapacity(count); - while (userCounts.size() < count + 1) { - userCounts.add(null); - } - ArrayList userSet = userCounts.get(count); - if (userSet == null) { - userSet = new ArrayList<>(); - } - userSet.add(user); - userCounts.set(count, userSet); + @Test + public void buildDataModel() { + long n1Id; + long n2Id; + try (Transaction tx = this.graphDb().beginTx()) { + Node n1 = tx.createNode(); + n1.setProperty("name", "n1"); + Node n2 = tx.createNode(); + n2.setProperty("name", "n2"); + n1.createRelationshipTo(n2, RelationshipType.withName("LIKES")); + n1Id = n1.getId(); + n2Id = n2.getId(); + debugNode(n1); + debugNode(n2); + tx.commit(); } - if (userCounts.size() > 1) { - System.out.println("\tTop 20 users (nodes: users):"); - for (int ui = userCounts.size() - 1, i = 0; i < 20 && ui >= 0; ui--) { - ArrayList userSet = userCounts.get(ui); - if (userSet != null && userSet.size() > 0) { - i++; - StringBuilder us = new StringBuilder(); - for (long user : userSet) { - Node userNode = tx.getNodeById(user); - int csCount = 0; - for (@SuppressWarnings("unused") - Relationship rel : userNode.getRelationships(Direction.INCOMING, OSMRelation.USER)) { - csCount++; - } - String name = userNames.get(user); - Long uid = userIds.get(user); - if (us.length() > 0) { - us.append(", "); - } - us.append(String.format("%s (uid=%d, id=%d, changesets=%d)", name, uid, user, csCount)); - } - System.out.println("\t\t" + ui + ": " + us.toString()); - } + try (Transaction tx = this.graphDb().beginTx()) { + for (Node n : tx.getAllNodes()) { + debugNode(n); } + tx.commit(); } } - protected void runImport(String osm, boolean includePoints) throws Exception { - // TODO: Consider merits of using dependency data in target/osm, - // downloaded by maven, as done in TestSpatial, versus the test data - // commited to source code as done here - String osmPath = checkOSMFile(osm); - if (osmPath == null) { - return; + private void debugNode(Node node) { + Map properties = node.getProperties(); + System.out.println(node + " has " + properties.size() + " properties"); + for (Map.Entry property : properties.entrySet()) { + System.out.println(" key: " + property.getKey()); + System.out.println(" value: " + property.getValue()); } - printDatabaseStats(); - loadTestOsmData(osm, osmPath, includePoints); - checkOSMLayer(graphDb(), osm); - printDatabaseStats(); - } - - protected void loadTestOsmData(String layerName, String osmPath, boolean includePoints) throws Exception { - System.out.printf("\n=== Loading layer '%s' from %s, includePoints=%b ===\n", layerName, osmPath, includePoints); - long start = System.currentTimeMillis(); - // tag::importOsm[] START SNIPPET: importOsm - OSMImporter importer = new OSMImporter(layerName, new ConsoleListener()); - importer.setCharset(StandardCharsets.UTF_8); - importer.importFile(graphDb(), osmPath, includePoints, 5000); - // end::importOsm[] END SNIPPET: importOsm - // Weird hack to force GC on large loads - if (System.currentTimeMillis() - start > 300000) { - for (int i = 0; i < 3; i++) { - System.gc(); - Thread.sleep(1000); - } + Iterable relationships = node.getRelationships(); + long count = StreamSupport.stream(relationships.spliterator(), false).count(); + System.out.println(node + " has " + count + " relationships"); + for (Relationship relationship : relationships) { + System.out.println(" (" + relationship.getStartNode() + ")-[:" + relationship.getType() + "]->(" + relationship.getEndNode() + ")"); } - importer.reIndex(graphDb(), 1000, includePoints); } } diff --git a/src/test/java/org/neo4j/gis/spatial/TestOSMImportBase.java b/src/test/java/org/neo4j/gis/spatial/TestOSMImportBase.java new file mode 100644 index 000000000..450d8baea --- /dev/null +++ b/src/test/java/org/neo4j/gis/spatial/TestOSMImportBase.java @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2010-2020 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j Spatial. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.gis.spatial; + +import org.geotools.data.DataStore; +import org.geotools.data.neo4j.Neo4jSpatialDataStore; +import org.geotools.data.simple.SimpleFeatureCollection; +import org.junit.jupiter.api.Assertions; +import org.locationtech.jts.geom.Envelope; +import org.locationtech.jts.geom.Geometry; +import org.neo4j.gis.spatial.index.IndexManager; +import org.neo4j.gis.spatial.osm.*; +import org.neo4j.gis.spatial.osm.OSMDataset.Way; +import org.neo4j.gis.spatial.pipes.osm.OSMGeoPipeline; +import org.neo4j.graphdb.*; +import org.neo4j.internal.kernel.api.security.SecurityContext; +import org.neo4j.kernel.internal.GraphDatabaseAPI; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class TestOSMImportBase extends Neo4jTestCase { + + protected static String checkOSMFile(String osm) { + File osmFile = new File(osm); + if (!osmFile.exists()) { + osmFile = new File(new File("osm"), osm); + if (!osmFile.exists()) { + return null; + } + } + return osmFile.getPath(); + } + + protected static void checkOSMLayer(GraphDatabaseService db, String layerName) throws IOException { + int indexCount; + try (Transaction tx = db.beginTx()) { + SpatialDatabaseService spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) db, SecurityContext.AUTH_DISABLED)); + OSMLayer layer = (OSMLayer) spatial.getOrCreateLayer(tx, layerName, OSMGeometryEncoder.class, OSMLayer.class); + Assertions.assertNotNull(layer.getIndex(), "OSM Layer index should not be null"); + Assertions.assertNotNull(layer.getIndex().getBoundingBox(tx), "OSM Layer index envelope should not be null"); + Envelope bbox = Utilities.fromNeo4jToJts(layer.getIndex().getBoundingBox(tx)); + debugEnvelope(bbox, layerName, Constants.PROP_BBOX); + // ((RTreeIndex)layer.getIndex()).debugIndexTree(); + indexCount = checkIndexCount(tx, layer); + checkChangesetsAndUsers(tx, layer); + checkOSMSearch(tx, layer); + tx.commit(); + } + checkFeatureCount(db, indexCount, layerName); + } + + public static void checkOSMSearch(Transaction tx, OSMLayer layer) { + OSMDataset osm = OSMDataset.fromLayer(tx, layer); + Way way = null; + int count = 0; + for (Way wayNode : osm.getWays(tx)) { + // Do not `break` from the loop or experience the RelationshipTraversalCursor leak bug in Neo4j 4.3 + if (count++ <= 100) { + way = wayNode; + } + } + Assertions.assertNotNull(way, "Should be at least one way"); + Envelope bbox = way.getEnvelope(); + runSearches(tx, layer, bbox, true); + org.neo4j.gis.spatial.rtree.Envelope layerBBox = layer.getIndex().getBoundingBox(tx); + double[] centre = layerBBox.centre(); + double width = layerBBox.getWidth(0) / 100.0; + double height = layerBBox.getWidth(1) / 100.0; + bbox = new Envelope(centre[0] - width, centre[0] + width, centre[1] - height, centre[1] + height); + runSearches(tx, layer, bbox, false); + } + + private static void runSearches(Transaction tx, OSMLayer layer, Envelope bbox, boolean willHaveResult) { + for (int i = 0; i < 4; i++) { + Geometry searchArea = layer.getGeometryFactory().toGeometry(bbox); + runWithinSearch(tx, layer, searchArea, willHaveResult); + bbox.expandBy(bbox.getWidth(), bbox.getHeight()); + } + } + + private static void runWithinSearch(Transaction tx, OSMLayer layer, Geometry searchArea, boolean willHaveResult) { + long start = System.currentTimeMillis(); + List results = OSMGeoPipeline.startWithinSearch(tx, layer, searchArea).toSpatialDatabaseRecordList(); + long time = System.currentTimeMillis() - start; + System.out.println("Took " + time + "ms to find " + results.size() + " search results in layer " + layer.getName() + + " using search within " + searchArea); + if (willHaveResult) + Assertions.assertTrue(results.size() > 0, "Should be at least one result, but got zero"); + } + + public static void debugEnvelope(Envelope bbox, String layer, String name) { + System.out.println("Layer '" + layer + "' has envelope '" + name + "': " + bbox); + System.out.println("\tX: [" + bbox.getMinX() + ":" + bbox.getMaxX() + "]"); + System.out.println("\tY: [" + bbox.getMinY() + ":" + bbox.getMaxY() + "]"); + } + + public static int checkIndexCount(Transaction tx, Layer layer) { + if (layer.getIndex().count(tx) < 1) { + System.out.println("Warning: index count zero: " + layer.getName()); + } + System.out.println("Layer '" + layer.getName() + "' has " + layer.getIndex().count(tx) + " entries in the index"); + return layer.getIndex().count(tx); + } + + public static void checkFeatureCount(GraphDatabaseService db, int indexCount, String layerName) throws IOException { + DataStore store = new Neo4jSpatialDataStore(db); + SimpleFeatureCollection features = store.getFeatureSource(layerName).getFeatures(); + int featuresSize = features.size(); + System.out.println("Layer '" + layerName + "' has " + featuresSize + " features"); + Assertions.assertEquals(indexCount, featuresSize, "FeatureCollection.size for layer '" + layerName + "' not the same as index count"); + } + + private static void checkChangesetsAndUsers(Transaction tx, OSMLayer layer) { + double totalMatch = 0.0; + int waysMatched = 0; + int waysCounted = 0; + int nodesCounted = 0; + int waysMissing = 0; + int nodesMissing = 0; + int usersMissing = 0; + float maxMatch = 0.0f; + float minMatch = 1.0f; + HashMap userNodeCount = new HashMap<>(); + HashMap userNames = new HashMap<>(); + HashMap userIds = new HashMap<>(); + OSMDataset dataset = OSMDataset.fromLayer(tx, layer); + for (Node way : dataset.getAllWayNodes(tx)) { + int node_count = 0; + int match_count = 0; + Assertions.assertNull(way.getProperty("changeset", null), "Way has changeset property"); + Node wayChangeset = dataset.getChangeset(way); + if (wayChangeset != null) { + long wayCS = (Long) wayChangeset.getProperty("changeset"); + for (Node node : dataset.getWayNodes(way)) { + Assertions.assertNull(node.getProperty("changeset", null), "Node has changeset property"); + Node nodeChangeset = dataset.getChangeset(node); + if (nodeChangeset == null) { + nodesMissing++; + } else { + long nodeCS = (Long) nodeChangeset.getProperty("changeset"); + if (nodeChangeset.equals(wayChangeset)) { + match_count++; + } else { + Assertions.assertNotEquals(wayCS, nodeCS, "Two changeset nodes should not have the same changeset number: way(" + wayCS + ")==node(" + nodeCS + ")"); + } + Node user = dataset.getUser(nodeChangeset); + if (user != null) { + long userid = user.getId(); + if (userNodeCount.containsKey(userid)) { + userNodeCount.put(userid, userNodeCount.get(userid) + 1); + } else { + userNodeCount.put(userid, 1); + userNames.put(userid, (String) user.getProperty("name", null)); + userIds.put(userid, (Long) user.getProperty("uid", null)); + } + } else { + if (usersMissing++ < 10) { + System.out.println("Changeset " + nodeCS + " should have user: " + nodeChangeset); + } + } + } + node_count++; + } + } else { + waysMissing++; + } + if (node_count > 0) { + waysMatched++; + float match = ((float) match_count) / ((float) node_count); + maxMatch = Math.max(maxMatch, match); + minMatch = Math.min(minMatch, match); + totalMatch += match; + nodesCounted += node_count; + } + waysCounted++; + } + System.out.println("After checking " + waysCounted + " ways:"); + System.out.println("\twe found " + waysMatched + " ways with an average of " + (nodesCounted / waysMatched) + " nodes"); + System.out.println("\tand an average of " + (100.0 * totalMatch / waysMatched) + "% matching changesets"); + System.out.println("\twith min-match " + (100.0 * minMatch) + "% and max-match " + (100.0 * maxMatch) + "%"); + System.out.println("\tWays missing changsets: " + waysMissing); + System.out.println("\tNodes missing changsets: " + nodesMissing + " (~" + (nodesMissing / waysMatched) + " / way)"); + System.out.println("\tUnique users: " + userNodeCount.size() + " (with " + usersMissing + " changeset missing users)"); + ArrayList> userCounts = new ArrayList<>(); + for (long user : userNodeCount.keySet()) { + int count = userNodeCount.get(user); + userCounts.ensureCapacity(count); + while (userCounts.size() < count + 1) { + userCounts.add(null); + } + ArrayList userSet = userCounts.get(count); + if (userSet == null) { + userSet = new ArrayList<>(); + } + userSet.add(user); + userCounts.set(count, userSet); + } + if (userCounts.size() > 1) { + System.out.println("\tTop 20 users (nodes: users):"); + for (int ui = userCounts.size() - 1, i = 0; i < 20 && ui >= 0; ui--) { + ArrayList userSet = userCounts.get(ui); + if (userSet != null && userSet.size() > 0) { + i++; + StringBuilder us = new StringBuilder(); + for (long user : userSet) { + Node userNode = tx.getNodeById(user); + int csCount = 0; + for (@SuppressWarnings("unused") + Relationship rel : userNode.getRelationships(Direction.INCOMING, OSMRelation.USER)) { + csCount++; + } + String name = userNames.get(user); + Long uid = userIds.get(user); + if (us.length() > 0) { + us.append(", "); + } + us.append(String.format("%s (uid=%d, id=%d, changesets=%d)", name, uid, user, csCount)); + } + System.out.println("\t\t" + ui + ": " + us); + } + } + } + } + + protected void runImport(String osm, boolean includePoints) throws Exception { + // TODO: Consider merits of using dependency data in target/osm, + // downloaded by maven, as done in TestSpatial, versus the test data + // committed to source code as done here + String osmPath = checkOSMFile(osm); + if (osmPath == null) { + return; + } + printDatabaseStats(); + loadTestOsmData(osm, osmPath, includePoints); + checkOSMLayer(graphDb(), osm); + printDatabaseStats(); + } + + protected void loadTestOsmData(String layerName, String osmPath, boolean includePoints) throws Exception { + System.out.printf("\n=== Loading layer '%s' from %s, includePoints=%b ===\n", layerName, osmPath, includePoints); + long start = System.currentTimeMillis(); + // tag::importOsm[] START SNIPPET: importOsm + OSMImporter importer = new OSMImporter(layerName, new ConsoleListener()); + importer.setCharset(StandardCharsets.UTF_8); + importer.importFile(graphDb(), osmPath, includePoints, 5000); + // end::importOsm[] END SNIPPET: importOsm + // Weird hack to force GC on large loads + if (System.currentTimeMillis() - start > 300000) { + for (int i = 0; i < 3; i++) { + System.gc(); + Thread.sleep(1000); + } + } + importer.reIndex(graphDb(), 1000, includePoints); + } +} diff --git a/src/test/java/org/neo4j/gis/spatial/TestProcess.java b/src/test/java/org/neo4j/gis/spatial/TestProcess.java index ad87837f8..988602ce3 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestProcess.java +++ b/src/test/java/org/neo4j/gis/spatial/TestProcess.java @@ -19,6 +19,7 @@ */ package org.neo4j.gis.spatial; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.io.ParseException; @@ -29,7 +30,6 @@ import org.geotools.process.Processors; import org.geotools.process.Progress; import org.geotools.util.KVP; -import org.junit.Test; import org.opengis.feature.type.Name; import java.util.Map; diff --git a/src/test/java/org/neo4j/gis/spatial/TestReadOnlyTransactions.java b/src/test/java/org/neo4j/gis/spatial/TestReadOnlyTransactions.java index 40f1621f2..00e1e6558 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestReadOnlyTransactions.java +++ b/src/test/java/org/neo4j/gis/spatial/TestReadOnlyTransactions.java @@ -1,22 +1,22 @@ package org.neo4j.gis.spatial; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.neo4j.dbms.api.DatabaseManagementService; -import org.neo4j.graphdb.GraphDatabaseService; -import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.RelationshipType; -import org.neo4j.graphdb.Transaction; +import org.neo4j.graphdb.*; import org.neo4j.io.fs.FileUtils; import org.neo4j.test.TestDatabaseManagementServiceBuilder; import java.io.File; import java.io.IOException; import java.nio.file.Path; +import java.util.Map; +import java.util.Spliterators; +import java.util.stream.StreamSupport; -import static org.junit.Assert.assertEquals; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; +import static org.junit.jupiter.api.Assertions.*; /** * This test was written to test the subtle behavior of nested transactions in the Neo4j 1.x-3.x code. @@ -32,20 +32,21 @@ public class TestReadOnlyTransactions { private static final Path basePath = new File("target/var").toPath(); private static final String dbPrefix = "neo4j-db"; - private long storePrefix; + private static long storePrefix; private static long n1Id = 0L; private static long n2Id = 0L; - @Before + @BeforeEach public void setUp() throws Exception { storePrefix++; + System.out.println("Creating store at " + dbPrefix + storePrefix); this.databases = new TestDatabaseManagementServiceBuilder(basePath.resolve(dbPrefix + storePrefix)).impermanent().build(); this.graph = databases.database(DEFAULT_DATABASE_NAME); buildDataModel(); } - @After + @AfterEach public void tearDown() { databases.shutdown(); try { @@ -76,8 +77,8 @@ private void readNames(Transaction tx) { String n2Name = (String) n2.getProperty("name"); System.out.println("First node: " + n1Name); System.out.println("Second node: " + n2Name); - assertEquals("Name does not match", n1Name, "n1"); - assertEquals("Name does not match", n2Name, "n2"); + assertEquals("n1", n1Name, "Name does not match"); + assertEquals("n2", n2Name, "Name does not match"); } private void readNamesWithNestedTransaction(boolean outer, boolean inner) { @@ -98,6 +99,7 @@ private void readNamesWithNestedTransaction(boolean outer, boolean inner) { public void testNormalTransaction() { try (Transaction tx = graph.beginTx()) { readNames(tx); + tx.commit(); } } @@ -121,8 +123,7 @@ public void testNestedTransactionSF() { try { readNamesWithNestedTransaction(true, false); } catch (Exception e) { - assertEquals("Expected transaction failure from RollbackException", - "Transaction rolled back even if marked as successful", e.getCause().getMessage()); + assertEquals("Transaction rolled back even if marked as successful", e.getCause().getMessage(), "Expected transaction failure from RollbackException"); } } } diff --git a/src/test/java/org/neo4j/gis/spatial/TestRemove.java b/src/test/java/org/neo4j/gis/spatial/TestRemove.java index fcb6d7dc6..33a9d6a8d 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestRemove.java +++ b/src/test/java/org/neo4j/gis/spatial/TestRemove.java @@ -19,9 +19,9 @@ */ package org.neo4j.gis.spatial; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; -import org.junit.Test; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.graphdb.Transaction; import org.neo4j.internal.kernel.api.security.SecurityContext; diff --git a/src/test/java/org/neo4j/gis/spatial/TestSimplePointLayer.java b/src/test/java/org/neo4j/gis/spatial/TestSimplePointLayer.java index 398398a6b..cb25f447d 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestSimplePointLayer.java +++ b/src/test/java/org/neo4j/gis/spatial/TestSimplePointLayer.java @@ -19,13 +19,13 @@ */ package org.neo4j.gis.spatial; +import junit.framework.AssertionFailedError; +import org.geotools.data.neo4j.StyledImageExporter; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.CoordinateList; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; -import junit.framework.AssertionFailedError; -import org.geotools.data.neo4j.StyledImageExporter; -import org.junit.Test; import org.neo4j.gis.spatial.encoders.neo4j.Neo4jCRS; import org.neo4j.gis.spatial.encoders.neo4j.Neo4jPoint; import org.neo4j.gis.spatial.index.IndexManager; @@ -46,7 +46,7 @@ import java.util.List; import java.util.function.Consumer; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class TestSimplePointLayer extends Neo4jTestCase { @@ -138,7 +138,7 @@ public void testNeoTextLayer() { inTx(tx -> { SimplePointLayer layer = spatial.createSimplePointLayer(tx, layerName); assertNotNull(layer); - assertNotNull("layer name is not null", layer.getName()); + assertNotNull(layer.getName(), "layer name is not null"); for (Coordinate coordinate : makeCoordinateDataFromTextFile("NEO4J-SPATIAL.txt", testOrigin)) { SpatialRecord record = layer.add(tx, coordinate); assertNotNull(record); @@ -307,7 +307,7 @@ private void checkPointOrder(List results) { GeoPipeFlow second = results.get(i + 1); double d1 = (Double) first.getProperties().get(OrthodromicDistance.DISTANCE); double d2 = (Double) second.getProperties().get(OrthodromicDistance.DISTANCE); - assertTrue("Point at position " + i + " (d=" + d1 + ") must be closer than point at position " + (i + 1) + " (d=" + d2 + ")", d1 <= d2); + assertTrue(d1 <= d2, "Point at position " + i + " (d=" + d1 + ") must be closer than point at position " + (i + 1) + " (d=" + d2 + ")"); } } @@ -386,7 +386,7 @@ private void saveResultsAsImage(List results, String la } } - @SuppressWarnings("unchecked") + @SuppressWarnings({"SameParameterValue"}) private static Coordinate[] makeCoordinateDataFromTextFile(String textFile, Coordinate origin) { CoordinateList data = new CoordinateList(); try { @@ -410,7 +410,6 @@ private static Coordinate[] makeCoordinateDataFromTextFile(String textFile, Coor return data.toCoordinateArray(); } - @SuppressWarnings("unchecked") private static Coordinate[] makeDensePointData() { CoordinateList data = new CoordinateList(); Coordinate origin = new Coordinate(13.0, 55.6); diff --git a/src/test/java/org/neo4j/gis/spatial/TestSpatial.java b/src/test/java/org/neo4j/gis/spatial/TestSpatial.java index 9bb88fc64..43c4b1243 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestSpatial.java +++ b/src/test/java/org/neo4j/gis/spatial/TestSpatial.java @@ -19,29 +19,30 @@ */ package org.neo4j.gis.spatial; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; - -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.neo4j.gis.spatial.filter.SearchIntersect; +import org.neo4j.gis.spatial.filter.SearchRecords; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.gis.spatial.index.LayerIndexReader; import org.neo4j.gis.spatial.osm.OSMDataset; +import org.neo4j.gis.spatial.osm.OSMImporter; import org.neo4j.gis.spatial.osm.OSMLayer; import org.neo4j.gis.spatial.rtree.Envelope; import org.neo4j.gis.spatial.rtree.NullListener; -import org.neo4j.gis.spatial.filter.SearchIntersect; -import org.neo4j.gis.spatial.filter.SearchRecords; -import org.neo4j.gis.spatial.osm.OSMImporter; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.internal.kernel.api.security.SecurityContext; import org.neo4j.kernel.internal.GraphDatabaseAPI; -import static org.junit.Assert.*; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; + +import static org.junit.jupiter.api.Assertions.fail; /** *

@@ -87,7 +88,7 @@ public class TestSpatial extends Neo4jTestCase { private final HashMap geomStats = new HashMap<>(); private final String spatialTestMode = System.getProperty("spatial.test.mode"); - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -254,10 +255,10 @@ private void testSpatialIndex(String layerName) { SpatialDatabaseService spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) graphDb(), SecurityContext.AUTH_DISABLED)); try (Transaction tx = graphDb().beginTx()) { Layer layer = spatial.getLayer(tx, layerName); - OSMDataset.fromLayer(tx, (OSMLayer) layer); // force lookup if (layer == null || layer.getIndex() == null || layer.getIndex().count(tx) < 1) { fail("Layer not loaded: " + layerName); } + OSMDataset.fromLayer(tx, (OSMLayer) layer); // force lookup LayerIndexReader fakeIndex = new SpatialIndexPerformanceProxy(new FakeIndex(layer, spatial.indexManager)); LayerIndexReader rtreeIndex = new SpatialIndexPerformanceProxy(layer.getIndex()); @@ -267,7 +268,7 @@ private void testSpatialIndex(String layerName) { assertEnvelopeEquals(fakeIndex.getBoundingBox(tx), rtreeIndex.getBoundingBox(tx)); System.out.println("RTreeIndex count: " + rtreeIndex.count(tx)); - assertEquals(fakeIndex.count(tx), rtreeIndex.count(tx)); + Assertions.assertEquals(fakeIndex.count(tx), rtreeIndex.count(tx)); Envelope bbox = layerTestEnvelope.get(layerName); @@ -293,7 +294,7 @@ private void testSpatialIndex(String layerName) { props.append(prop).append(": ").append(r.getProperty(tx, prop)); } - System.out.println("\tRTreeIndex result[" + ri + "]: " + r.getNodeId() + ":" + r.getType() + " - " + r.toString() + ": PROPS[" + props + "]"); + System.out.println("\tRTreeIndex result[" + ri + "]: " + r.getNodeId() + ":" + r.getType() + " - " + r + ": PROPS[" + props + "]"); } else if (ri == 10) { System.out.println("\t.. and " + (count - ri) + " more .."); } @@ -313,8 +314,7 @@ private void testSpatialIndex(String layerName) { System.out.println("\tOnly first character matched: test[" + testData + "] == result[" + r + "]"); } */ } else { - System.err.println("\tNo name or id in RTreeIndex result: " + r.getNodeId() + ":" + r.getType() + " - " - + r.toString()); + System.err.println("\tNo name or id in RTreeIndex result: " + r.getNodeId() + ":" + r.getType() + " - " + r); } } @@ -345,13 +345,13 @@ private void testSpatialIndex(String layerName) { } private void assertEnvelopeEquals(Envelope a, Envelope b) { - assertNotNull(a); - assertNotNull(b); - assertEquals(a.getDimension(), b.getDimension()); + Assertions.assertNotNull(a); + Assertions.assertNotNull(b); + Assertions.assertEquals(a.getDimension(), b.getDimension()); for (int i = 0; i < a.getDimension(); i++) { - assertEquals(a.getMin(i), b.getMin(i), 0); - assertEquals(a.getMax(i), b.getMax(i), 0); + Assertions.assertEquals(a.getMin(i), b.getMin(i), 0); + Assertions.assertEquals(a.getMax(i), b.getMax(i), 0); } } diff --git a/src/test/java/org/neo4j/gis/spatial/TestSpatialQueries.java b/src/test/java/org/neo4j/gis/spatial/TestSpatialQueries.java index 89e39469d..d3c4c3c03 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestSpatialQueries.java +++ b/src/test/java/org/neo4j/gis/spatial/TestSpatialQueries.java @@ -19,11 +19,12 @@ */ package org.neo4j.gis.spatial; +import org.hamcrest.MatcherAssert; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; -import org.junit.Test; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.gis.spatial.pipes.GeoPipeline; import org.neo4j.graphdb.Transaction; @@ -31,7 +32,8 @@ import org.neo4j.kernel.internal.GraphDatabaseAPI; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class TestSpatialQueries extends Neo4jTestCase { @@ -72,7 +74,7 @@ public void testSearchClosestWithShortLongLineStrings() throws ParseException { closestGeom = geom; } } - assertNotNull("Expected to find a clistestGeom", closestGeom); + assertNotNull(closestGeom, "Expected to find a clistestGeom"); System.out.println("Found closest: " + closestGeom); System.out.println(); @@ -86,7 +88,7 @@ public void testSearchClosestWithShortLongLineStrings() throws ParseException { .getMin("Distance"); for (SpatialRecord result : pipeline) { System.out.println("\tGot search result: " + result); - assertEquals("Did not find the closest", closestGeom.toString(), result.getGeometry().toString()); + assertEquals(closestGeom.toString(), result.getGeometry().toString(), "Did not find the closest"); } tx.commit(); } @@ -103,7 +105,7 @@ public void testSearchClosestWithShortLongLineStrings() throws ParseException { System.out.println("Searching for geometries close to " + point + " within " + env); for (SpatialRecord result : pipeline) { System.out.println("\tGot search result: " + result); - assertEquals("Did not find the closest", closestGeom.toString(), result.getGeometry().toString()); + assertEquals(closestGeom.toString(), result.getGeometry().toString(), "Did not find the closest"); } tx.commit(); } @@ -118,7 +120,7 @@ public void testSearchClosestWithShortLongLineStrings() throws ParseException { System.out.println("Searching for geometries close to " + point + " within buffer " + buffer); for (SpatialRecord result : pipeline) { System.out.println("\tGot search result: " + result); - assertEquals("Did not find the closest", closestGeom.toString(), result.getGeometry().toString()); + assertEquals(closestGeom.toString(), result.getGeometry().toString(), "Did not find the closest"); } tx.commit(); } @@ -145,7 +147,7 @@ public void testSearchClosestWithShortLongLineStrings() throws ParseException { System.out.println("Searching for geometries close to " + point + " within automatic window designed to get about " + limit + " geometries"); for (SpatialRecord result : pipeline) { System.out.println("\tGot search result: " + result); - assertThat("Did not find the closest", result.getGeometry().toString(), is(closestGeom.toString())); + MatcherAssert.assertThat("Did not find the closest", result.getGeometry().toString(), is(closestGeom.toString())); } tx.commit(); } diff --git a/src/test/java/org/neo4j/gis/spatial/TestSpatialUtils.java b/src/test/java/org/neo4j/gis/spatial/TestSpatialUtils.java index 0bd725bba..48f4f6c61 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestSpatialUtils.java +++ b/src/test/java/org/neo4j/gis/spatial/TestSpatialUtils.java @@ -19,13 +19,13 @@ */ package org.neo4j.gis.spatial; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LengthIndexedLine; import org.locationtech.jts.linearref.LocationIndexedLine; -import org.junit.Test; import org.neo4j.gis.spatial.SpatialTopologyUtils.PointResult; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.gis.spatial.osm.OSMDataset; @@ -36,11 +36,10 @@ import org.neo4j.kernel.internal.GraphDatabaseAPI; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class TestSpatialUtils extends Neo4jTestCase { @@ -62,17 +61,17 @@ public void testJTSLinearRef() { Layer layer = spatial.getLayer(tx, "jts"); // Now test the new API in the topology utils Point point = SpatialTopologyUtils.locatePoint(layer, geometry, 1.5, 0.5); - assertEquals("X location incorrect", 0.5, point.getX(), delta); - assertEquals("Y location incorrect", 1.5, point.getY(), delta); + assertEquals(0.5, point.getX(), delta, "X location incorrect"); + assertEquals(1.5, point.getY(), delta, "Y location incorrect"); point = SpatialTopologyUtils.locatePoint(layer, geometry, 1.5, -0.5); - assertEquals("X location incorrect", 0.5, point.getX(), delta); - assertEquals("Y location incorrect", 0.5, point.getY(), delta); + assertEquals(0.5, point.getX(), delta, "X location incorrect"); + assertEquals(0.5, point.getY(), delta, "Y location incorrect"); point = SpatialTopologyUtils.locatePoint(layer, geometry, 0.5, 0.5); - assertEquals("X location incorrect", -0.5, point.getX(), delta); - assertEquals("Y location incorrect", 0.5, point.getY(), delta); + assertEquals(-0.5, point.getX(), delta, "X location incorrect"); + assertEquals(0.5, point.getY(), delta, "Y location incorrect"); point = SpatialTopologyUtils.locatePoint(layer, geometry, 0.5, -0.5); - assertEquals("X location incorrect", 0.5, point.getX(), delta); - assertEquals("Y location incorrect", 0.5, point.getY(), delta); + assertEquals(0.5, point.getX(), delta, "X location incorrect"); + assertEquals(0.5, point.getY(), delta, "Y location incorrect"); tx.commit(); } } @@ -121,20 +120,19 @@ public void testSnapping() throws Exception { printDatabaseStats(); // Define dynamic layers - List layers = new ArrayList<>(); SpatialDatabaseService spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) graphDb(), SecurityContext.AUTH_DISABLED)); try(Transaction tx = graphDb().beginTx()) { OSMLayer osmLayer = (OSMLayer) spatial.getLayer(tx, osm); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "primary")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "secondary")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "tertiary")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "residential")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "footway")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "cycleway")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "track")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", "path")); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "railway", null)); - layers.add(osmLayer.addSimpleDynamicLayer(tx, "highway", null)); + osmLayer.addSimpleDynamicLayer(tx, "highway", "primary"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "secondary"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "tertiary"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "residential"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "footway"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "cycleway"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "track"); + osmLayer.addSimpleDynamicLayer(tx, "highway", "path"); + osmLayer.addSimpleDynamicLayer(tx, "railway", null); + osmLayer.addSimpleDynamicLayer(tx, "highway", null); tx.commit(); } @@ -150,7 +148,7 @@ public void testSnapping() throws Exception { resultsLayer.add(tx, point, fieldsNames, new Object[]{0L, "Point to snap", 0L}); for (String layerName : new String[]{"railway", "highway-residential"}) { Layer layer = osmLayer.getLayer(tx, layerName); - assertNotNull("Missing layer: " + layerName, layer); + assertNotNull(layer, "Missing layer: " + layerName); System.out.println("Closest features in " + layerName + " to point " + point + ":"); List edgeResults = SpatialTopologyUtils.findClosestEdges(tx, point, layer); for (PointResult result : edgeResults) { @@ -166,6 +164,7 @@ public void testSnapping() throws Exception { SpatialDatabaseRecord wayRecord = closest.getValue(); OSMDataset.Way way = ((OSMDataset) osmLayer.getDataset()).getWayFrom(wayRecord.getGeomNode()); OSMDataset.WayPoint wayPoint = way.getPointAt(closestPoint.getCoordinate()); + // TODO: presumably we meant to assert something here? } } tx.commit(); @@ -173,6 +172,7 @@ public void testSnapping() throws Exception { } + @SuppressWarnings("SameParameterValue") private void loadTestOsmData(String layerName, int commitInterval) throws Exception { System.out.println("\n=== Loading layer " + layerName + " from " + layerName + " ==="); OSMImporter importer = new OSMImporter(layerName); @@ -180,5 +180,4 @@ private void loadTestOsmData(String layerName, int commitInterval) throws Except importer.importFile(graphDb(), layerName, commitInterval); importer.reIndex(graphDb(), commitInterval); } - } diff --git a/src/test/java/org/neo4j/gis/spatial/TestsForDocs.java b/src/test/java/org/neo4j/gis/spatial/TestsForDocs.java index 4859da47a..37380f9fe 100644 --- a/src/test/java/org/neo4j/gis/spatial/TestsForDocs.java +++ b/src/test/java/org/neo4j/gis/spatial/TestsForDocs.java @@ -22,9 +22,9 @@ import org.geotools.data.DataStore; import org.geotools.data.neo4j.Neo4jSpatialDataStore; import org.geotools.data.simple.SimpleFeatureCollection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.neo4j.dbms.api.DatabaseManagementService; @@ -50,8 +50,8 @@ import java.util.HashMap; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; /** @@ -65,7 +65,7 @@ public class TestsForDocs { private DatabaseManagementService databases; private GraphDatabaseService graphDb; - @Before + @BeforeEach public void setUp() throws Exception { this.databases = new DatabaseManagementServiceBuilder(Path.of("target", "docs-db")).build(); this.graphDb = databases.database(DEFAULT_DATABASE_NAME); @@ -79,7 +79,7 @@ public void setUp() throws Exception { } } - @After + @AfterEach public void tearDown() { this.databases.shutdown(); this.databases = null; @@ -101,7 +101,7 @@ private void checkIndexAndFeatureCount(String layerName) throws IOException { System.out.println("Layer '" + layerName + "' has " + features.size() + " features"); try (Transaction tx = graphDb.beginTx()) { Layer layer = spatial.getLayer(tx, layerName); - assertEquals("FeatureCollection.size for layer '" + layer.getName() + "' not the same as index count", layer.getIndex().count(tx), features.size()); + assertEquals(layer.getIndex().count(tx), features.size(), "FeatureCollection.size for layer '" + layer.getName() + "' not the same as index count"); if (layer instanceof OSMLayer) checkOSMAPI(tx, (OSMLayer) layer); tx.commit(); @@ -132,7 +132,7 @@ private void checkOSMAPI(Transaction tx, OSMLayer layer) { for (long wayId : waysFound.keySet()) { System.out.println("\t" + wayId + ":\t" + waysFound.get(wayId) + ((wayId == way.getNode().getId()) ? "\t(original way)" : "")); } - assertTrue("Start way should be most found way", way.equals(osm.getWayFromId(tx, mostCommon))); + assertTrue(way.equals(osm.getWayFromId(tx, mostCommon)), "Start way should be most found way"); } private void importMapOSM(GraphDatabaseService db) throws Exception { diff --git a/src/test/java/org/neo4j/gis/spatial/TryWithResourceTest.java b/src/test/java/org/neo4j/gis/spatial/TryWithResourceTest.java index 61c26b41f..14cec27ea 100644 --- a/src/test/java/org/neo4j/gis/spatial/TryWithResourceTest.java +++ b/src/test/java/org/neo4j/gis/spatial/TryWithResourceTest.java @@ -1,6 +1,6 @@ package org.neo4j.gis.spatial; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; @@ -9,9 +9,10 @@ import java.io.File; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; +@SuppressWarnings("ConstantConditions") public class TryWithResourceTest { public static final String MESSAGE = "I want to see this"; diff --git a/src/test/java/org/neo4j/gis/spatial/index/LayerIndexTestBase.java b/src/test/java/org/neo4j/gis/spatial/index/LayerIndexTestBase.java index 0b0a736f8..9d34272e6 100644 --- a/src/test/java/org/neo4j/gis/spatial/index/LayerIndexTestBase.java +++ b/src/test/java/org/neo4j/gis/spatial/index/LayerIndexTestBase.java @@ -19,11 +19,11 @@ */ package org.neo4j.gis.spatial.index; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.*; import org.geotools.referencing.crs.DefaultGeographicCRS; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; import org.mockito.Matchers; import org.neo4j.dbms.api.DatabaseManagementService; import org.neo4j.gis.spatial.*; @@ -108,7 +108,7 @@ protected void addSimplePoint(SpatialIndexWriter index, double x, double y) { } } - @Before + @BeforeEach public void setup() throws IOException { File baseDir = new File("target/layers"); FileUtils.deleteDirectory(baseDir.toPath()); @@ -117,7 +117,7 @@ public void setup() throws IOException { spatial = new SpatialDatabaseService(new IndexManager((GraphDatabaseAPI) graph, SecurityContext.AUTH_DISABLED)); } - @After + @AfterEach public void tearDown() { if (graph != null) { databases.shutdown(); diff --git a/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesDocTest.java b/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesDocTest.java index f12e0cfcd..6dac86edb 100644 --- a/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesDocTest.java +++ b/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesDocTest.java @@ -19,12 +19,6 @@ */ package org.neo4j.gis.spatial.pipes; -import org.locationtech.jts.geom.Coordinate; -import org.locationtech.jts.geom.Envelope; -import org.locationtech.jts.geom.Geometry; -import org.locationtech.jts.geom.util.AffineTransformation; -import org.locationtech.jts.io.ParseException; -import org.locationtech.jts.io.WKTReader; import org.geotools.data.neo4j.Neo4jFeatureBuilder; import org.geotools.data.neo4j.StyledImageExporter; import org.geotools.feature.FeatureCollection; @@ -32,10 +26,16 @@ import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.crs.DefaultEngineeringCRS; import org.geotools.styling.Style; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.Envelope; +import org.locationtech.jts.geom.Geometry; +import org.locationtech.jts.geom.util.AffineTransformation; +import org.locationtech.jts.io.ParseException; +import org.locationtech.jts.io.WKTReader; import org.neo4j.annotations.documented.Documented; import org.neo4j.gis.spatial.*; import org.neo4j.gis.spatial.filter.SearchIntersectWindow; @@ -54,10 +54,10 @@ import java.awt.*; import java.io.File; import java.io.IOException; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME; public class GeoPipesDocTest extends AbstractJavaDocTestBase { @@ -109,10 +109,7 @@ public void filter_by_property() { @Test public void filter_by_window_intersection() { - assertEquals( - 1, - GeoPipeline.start(tx, osmLayer).windowIntersectionFilter(10, 40, 20, - 56.0583531).count()); + assertEquals(1, GeoPipeline.start(tx, osmLayer).windowIntersectionFilter(10, 40, 20, 56.0583531).count()); } /** @@ -147,9 +144,7 @@ public void search_within_geometry() throws CQLException { GeoPipeline pipeline = GeoPipeline .startWithinSearch(tx, osmLayer, osmLayer.getGeometryFactory().toGeometry(new Envelope(10, 20, 50, 60))); // end::search_within_geometry[] - assertEquals( - 2, - pipeline.count()); + assertEquals(2, pipeline.count()); } @Test @@ -228,10 +223,9 @@ public void translate_geometries() { public void calculate_area() { GeoPipeline pipeline = GeoPipeline.start(tx, boxesLayer).calculateArea().sort("Area"); - assertEquals((Double) pipeline.next().getProperties().get("Area"), - 1.0, 0); - assertEquals((Double) pipeline.next().getProperties().get("Area"), - 8.0, 0); + assertEquals((Double) pipeline.next().getProperties().get("Area"), 1.0, 0); + assertEquals((Double) pipeline.next().getProperties().get("Area"), 8.0, 0); + pipeline.reset(); } @Test @@ -240,6 +234,7 @@ public void calculate_length() { assertEquals((Double) pipeline.next().getProperties().get("Length"), 4.0, 0); assertEquals((Double) pipeline.next().getProperties().get("Length"), 12.0, 0); + pipeline.reset(); } @Test @@ -252,6 +247,7 @@ public void get_boundary_length() { assertEquals("LINEARRING (2 3, 2 5, 6 5, 6 3, 2 3)", second.getProperties().get("WellKnownText")); assertEquals((Double) first.getProperties().get("Length"), 4.0, 0); assertEquals((Double) second.getProperties().get("Length"), 12.0, 0); + pipeline.reset(); } /** @@ -276,6 +272,7 @@ public void get_buffer() { assertTrue(((Double) pipeline.next().getProperties().get("Area")) > 1); assertTrue(((Double) pipeline.next().getProperties().get("Area")) > 8); + pipeline.reset(); } /** @@ -298,10 +295,9 @@ public void get_centroid() { pipeline = GeoPipeline.start(tx, boxesLayer).toCentroid().createWellKnownText().copyDatabaseRecordProperties(tx).sort("name"); - assertEquals("POINT (12.5 26.5)", - pipeline.next().getProperties().get("WellKnownText")); - assertEquals("POINT (4 4)", - pipeline.next().getProperties().get("WellKnownText")); + assertEquals("POINT (12.5 26.5)", pipeline.next().getProperties().get("WellKnownText")); + assertEquals("POINT (4 4)", pipeline.next().getProperties().get("WellKnownText")); + pipeline.reset(); } /** @@ -349,8 +345,7 @@ public void get_convex_hull() { pipeline = GeoPipeline.start(tx, concaveLayer).toConvexHull().createWellKnownText(); - assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", - pipeline.next().getProperties().get("WellKnownText")); + assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", pipeline.next().getProperties().get("WellKnownText")); pipeline.reset(); } @@ -373,25 +368,20 @@ public void densify() { // end::densify[] addImageSnippet(concaveLayer, pipeline, getTitle(), Constants.GTYPE_POINT); + pipeline = GeoPipeline.start(tx, concaveLayer).toConvexHull().densify(5).createWellKnownText(); - pipeline = GeoPipeline.start(tx, concaveLayer).toConvexHull().densify(10).createWellKnownText(); - - assertEquals( - "POLYGON ((0 0, 0 5, 0 10, 5 10, 10 10, 10 5, 10 0, 5 0, 0 0))", - pipeline.next().getProperties().get("WellKnownText")); + String wkt = (String) pipeline.next().getProperties().get("WellKnownText"); pipeline.reset(); + assertEquals("POLYGON ((0 0, 0 5, 0 10, 5 10, 10 10, 10 5, 10 0, 5 0, 0 0))", wkt); } @Test public void json() { GeoPipeline pipeline = GeoPipeline.start(tx, boxesLayer).createJson().copyDatabaseRecordProperties(tx).sort("name"); - assertEquals( - "{\"type\":\"Polygon\",\"coordinates\":[[[12,26],[12,27],[13,27],[13,26],[12,26]]]}", - pipeline.next().getProperties().get("GeoJSON")); - assertEquals( - "{\"type\":\"Polygon\",\"coordinates\":[[[2,3],[2,5],[6,5],[6,3],[2,3]]]}", - pipeline.next().getProperties().get("GeoJSON")); + assertEquals("{\"type\":\"Polygon\",\"coordinates\":[[[12,26],[12,27],[13,27],[13,26],[12,26]]]}", pipeline.next().getProperties().get("GeoJSON")); + assertEquals("{\"type\":\"Polygon\",\"coordinates\":[[[2,3],[2,5],[6,5],[6,3],[2,3]]]}", pipeline.next().getProperties().get("GeoJSON")); + pipeline.reset(); } /** @@ -417,6 +407,7 @@ public void get_max_area() { pipeline = GeoPipeline.start(tx, boxesLayer).calculateArea().getMax("Area"); assertEquals((Double) pipeline.next().getProperties().get("Area"), 8.0, 0); + pipeline.reset(); } /** @@ -533,6 +524,7 @@ public void get_min_area() { pipeline = GeoPipeline.start(tx, boxesLayer).calculateArea().getMin("Area"); assertEquals((Double) pipeline.next().getProperties().get("Area"), 1.0, 0); + pipeline.reset(); } @Test @@ -544,7 +536,7 @@ public void extract_osm_points() { assertEquals(1, flow.getProperties().size()); String wkt = (String) flow.getProperties().get("WellKnownText"); - assertTrue(wkt.indexOf("POINT") == 0); + assertEquals(0, wkt.indexOf("POINT")); } assertEquals(24, count); @@ -624,22 +616,14 @@ public void extract_points() { @Test public void filter_by_null_property() { - assertEquals( - 2, - GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNullFilter("address").count()); - assertEquals( - 0, - GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNullFilter("name").count()); + assertEquals(2, GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNullFilter("address").count()); + assertEquals(0, GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNullFilter("name").count()); } @Test public void filter_by_not_null_property() { - assertEquals( - 0, - GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNotNullFilter("address").count()); - assertEquals( - 2, - GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNotNullFilter("name").count()); + assertEquals(0, GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNotNullFilter("address").count()); + assertEquals(2, GeoPipeline.start(tx, boxesLayer).copyDatabaseRecordProperties(tx).propertyNotNullFilter("name").count()); } @Test @@ -649,10 +633,9 @@ public void compute_distance() throws ParseException { GeoPipeline pipeline = GeoPipeline.start(tx, boxesLayer).calculateDistance( reader.read("POINT (0 0)")).sort("Distance"); - assertEquals( - 4, Math.round((Double) pipeline.next().getProperty(tx, "Distance"))); - assertEquals( - 29, Math.round((Double) pipeline.next().getProperty(tx, "Distance"))); + assertEquals(4, Math.round((Double) pipeline.next().getProperty(tx, "Distance"))); + assertEquals(29, Math.round((Double) pipeline.next().getProperty(tx, "Distance"))); + pipeline.reset(); } /** @@ -679,9 +662,7 @@ public void unite_all() { .unionAll() .createWellKnownText(); - assertEquals( - "POLYGON ((0 0, 0 5, 2 5, 2 6, 4 6, 4 10, 10 10, 10 4, 6 4, 6 2, 5 2, 5 0, 0 0))", - pipeline.next().getProperty(tx, "WellKnownText")); + assertEquals("POLYGON ((0 0, 0 5, 2 5, 2 6, 4 6, 4 10, 10 10, 10 4, 6 4, 6 2, 5 2, 5 0, 0 0))", pipeline.next().getProperty(tx, "WellKnownText")); try { pipeline.next(); @@ -714,8 +695,7 @@ public void intersect_all() { .intersectAll() .createWellKnownText(); - assertEquals("POLYGON ((4 5, 5 5, 5 4, 4 4, 4 5))", - pipeline.next().getProperty(tx, "WellKnownText")); + assertEquals("POLYGON ((4 5, 5 5, 5 4, 4 4, 4 5))", pipeline.next().getProperty(tx, "WellKnownText")); try { pipeline.next(); @@ -854,6 +834,7 @@ public void test_equality() throws Exception { assertEquals("different order", pipeline.next().getProperty(tx, "name")); assertEquals("topo equal", pipeline.next().getProperty(tx, "name")); assertFalse(pipeline.hasNext()); + pipeline.reset(); } private String getTitle() { @@ -979,18 +960,19 @@ private static void load() throws Exception { } } + @SuppressWarnings("SameParameterValue") private static void loadTestOsmData(String layerName, int commitInterval) throws Exception { String osmPath = "./" + layerName; System.out.println("\n=== Loading layer " + layerName + " from " + osmPath + " ==="); OSMImporter importer = new OSMImporter(layerName); - importer.setCharset(Charset.forName("UTF-8")); + importer.setCharset(StandardCharsets.UTF_8); importer.importFile(db, osmPath); importer.reIndex(db, commitInterval); } - @Before + @BeforeEach public void setUp() { gen.get().setGraph(db); try (Transaction tx = db.beginTx()) { @@ -1024,7 +1006,7 @@ public void setUp() { tx = db.beginTx(); } - @After + @AfterEach public void doc() { // gen.get().addSnippet( "graph", AsciidocHelper.createGraphViz( imgName , graphdb(), "graph"+getTitle() ) ); gen.get().addTestSourceSnippets(GeoPipesDocTest.class, "s_" + getTitle().toLowerCase()); @@ -1035,7 +1017,7 @@ public void doc() { } } - @BeforeClass + @BeforeAll public static void init() { databases = new TestDatabaseManagementServiceBuilder(new File("target/docs").toPath()).impermanent().build(); db = databases.database(DEFAULT_DATABASE_NAME); diff --git a/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesPerformanceTest.java b/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesPerformanceTest.java index d4e05e023..f855cb826 100644 --- a/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesPerformanceTest.java +++ b/src/test/java/org/neo4j/gis/spatial/pipes/GeoPipesPerformanceTest.java @@ -19,8 +19,9 @@ */ package org.neo4j.gis.spatial.pipes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; -import org.junit.Test; import org.neo4j.gis.spatial.*; import org.neo4j.gis.spatial.index.IndexManager; import org.neo4j.graphdb.Transaction; @@ -35,6 +36,7 @@ public class GeoPipesPerformanceTest extends Neo4jTestCase { private int records = 10000; private int chunkSize = records / 10; + @BeforeEach public void setUp() throws Exception { super.setUp(true); loadSamplePointData(); diff --git a/src/test/java/org/neo4j/gis/spatial/pipes/OrthodromicDistanceTest.java b/src/test/java/org/neo4j/gis/spatial/pipes/OrthodromicDistanceTest.java index 1a860dadf..3c32c252e 100644 --- a/src/test/java/org/neo4j/gis/spatial/pipes/OrthodromicDistanceTest.java +++ b/src/test/java/org/neo4j/gis/spatial/pipes/OrthodromicDistanceTest.java @@ -19,11 +19,11 @@ */ package org.neo4j.gis.spatial.pipes; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; -import org.junit.Test; import org.neo4j.gis.spatial.pipes.processing.OrthodromicDistance; import static org.hamcrest.CoreMatchers.equalTo; diff --git a/src/test/java/org/neo4j/gis/spatial/rtree/EnvelopeTests.java b/src/test/java/org/neo4j/gis/spatial/rtree/EnvelopeTests.java index ddb78df94..293ff8a89 100644 --- a/src/test/java/org/neo4j/gis/spatial/rtree/EnvelopeTests.java +++ b/src/test/java/org/neo4j/gis/spatial/rtree/EnvelopeTests.java @@ -19,12 +19,12 @@ */ package org.neo4j.gis.spatial.rtree; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class EnvelopeTests { @@ -74,6 +74,7 @@ private void testOverlaps(Envelope left, Envelope right, boolean intersects, dou assertThat(overlapMessage, right.overlap(left), closeTo(overlap, 0.000001)); } + @SuppressWarnings("SameParameterValue") private void testOverlaps(Envelope left, Envelope right, boolean intersects, double overlap, double overlapArea, double bboxArea) { testOverlaps(left, right, intersects, overlap); assertThat("Expected overlap area", left.intersection(right).getArea(), closeTo(overlapArea, 0.000001)); @@ -119,7 +120,7 @@ private void makeAndTestEnvelope(double[] min, double[] max, double[] width) { assertThat("Expected area to be correct", env.getArea(), equalTo(area)); assertThat("Expected copied area to be correct", env.getArea(), equalTo(copy.getArea())); assertThat("Expected intersected area to be correct", env.getArea(), equalTo(intersection.getArea())); - assertTrue("Expected copied envelope to intersect", env.intersects(copy)); + assertTrue(env.intersects(copy), "Expected copied envelope to intersect"); assertThat("Expected copied envelope to intersect completely", env.overlap(copy), equalTo(1.0)); } diff --git a/src/test/java/org/neo4j/gis/spatial/rtree/RTreeTests.java b/src/test/java/org/neo4j/gis/spatial/rtree/RTreeTests.java index 49ddac7f5..7898f1c65 100644 --- a/src/test/java/org/neo4j/gis/spatial/rtree/RTreeTests.java +++ b/src/test/java/org/neo4j/gis/spatial/rtree/RTreeTests.java @@ -20,9 +20,9 @@ package org.neo4j.gis.spatial.rtree; import org.geotools.data.neo4j.Neo4jFeatureBuilder; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.neo4j.dbms.api.DatabaseManagementService; @@ -47,7 +47,7 @@ public class RTreeTests { private TestRTreeIndex rtree; private RTreeImageExporter imageExporter; - @Before + @BeforeEach public void setup() { databases = new TestDatabaseManagementServiceBuilder(Path.of("target", "rtree")).impermanent().build(); db = databases.database(DEFAULT_DATABASE_NAME); @@ -65,7 +65,7 @@ public void setup() { } } - @After + @AfterEach public void teardown() { databases.shutdown(); } @@ -103,6 +103,7 @@ public void shouldMergeTwoPartiallyOverlappingTrees() throws IOException { } } + @SuppressWarnings("SameParameterValue") private RTreeIndex.NodeWithEnvelope createSimpleRTree(double minx, double maxx, int depth) { double[] min = new double[]{minx, minx}; double[] max = new double[]{maxx, maxx}; @@ -134,9 +135,10 @@ private RTreeIndex.NodeWithEnvelope createSimpleRTree(double minx, double maxx, } } + @SuppressWarnings("SameParameterValue") Envelope makeEnvelope(Envelope parent, double scaleFactor, double offsetX, double offsetY) { Envelope env = new Envelope(parent); - env.scaleBy(0.5); + env.scaleBy(scaleFactor); env.shiftBy(offsetX * env.getWidth(0), 0); env.shiftBy(offsetY * env.getWidth(1), 1); return env;